如何在Shiny应用中限制textInput接受的字符数量?

11

我希望我的Shiny应用(使用R语言编写)能够限制用户在textInput命令中输入的字符数。

我可以要求用户将字符数限制在50个以内,并且可以让该应用程序向用户发送消息,如果他没有遵守限制,则会有相应提示。但是更好的方法是在第一时间就防止用户超过字符限制。

欢迎提供建议。


展示你的代码,也许我们可以帮助你改进它。 - Vino
2个回答

9

您无法将自定义属性添加到textInput,您可能能够编写自定义函数来生成输入,但最好在JavaScript中执行此操作:

shinyjs::runjs("$('#inputName').attr('maxlength', 50)")

把这个放在我的 server.r 文件里非常好用,谢谢! - Iain
1
我认为像上面那样在客户端执行这个操作是一个很好的想法。(是的,shinyjs:: 调用是在服务器端,但实际的限制执行是由客户端浏览器完成的,正如应该做的那样)。 - maxheld
4
我已经在Shiny上记录了一个问题(https://github.com/rstudio/shiny/issues/3305),以支持在Shiny中使用`maxlength`。 - maxheld

1
例如,通过使用shinyBSstringr包:
library(stringr)
library(shinyBS)
string <- "Destrier ipsum dolor cold weirwood, consectetur adipisicing elit, sed full of terrors incididunt green dreams always pays his debts. Ut in his cups sandsilk, no foe may pass spearwife nisi ut aliquip we do not sow. Duis aute warrior feed it to the goats death before disgrace maidenhead dog the seven pariatur. Rouse me not cupidatat non proident, suckling pig culpa qui officia deserunt mollit we light the way."

    observe({
        if(str_length(string)>50) {
          newstring <-str_sub(string, end=50)
          createAlert(session, inputID = "alert_anchor",
            message = "You exceeded 50 character limit!",
            dismiss = TRUE,
            block = FALSE
            append = TRUE)
            updateTextInput(session, inputID, value = newstring)
    }

    })

    # remember to create alert to shiny UI
    # bsAlert(inputID = "alert_anchor")

演示页面的shinyBS: ShinyBS

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接