r-如何确保我在Shiny中的textInput只接受数值



我不想使用numericInput(),那么有其他方法可以解决这个问题吗?此外,我尝试限制字符数,错误消息有效,但updateTextInput()不起作用(它应该将原始输入缩减为仅5个字符(。任何帮助都将不胜感激!

app <- shinyApp(
ui <- fluidPage(

textInput("zipcode", label="Please enter your zipcode.", value = 66101)
),

server <- function(input, output, session) {

observeEvent(input$zipcode,{ #limits zipcode input to 5 numbers only
if(nchar(input$zipcode)>5 )
{
updateTextInput(session,'zipcode',value=substr(input$mytext,1,5))
showModal(modalDialog(
title = "Error!",
"Character limit exceeded!",
easyClose = TRUE
))
}
}
)
}
)

您错误地使用了input$mytext
尝试:

app <- shinyApp(
ui <- fluidPage(

textInput("zipcode", label="Please enter your zipcode.", value = 66101)
),

server <- function(input, output, session) {

observeEvent(input$zipcode,{ #limits zipcode input to 5 numbers only
cat(suppressWarnings(is.na(as.numeric(input$zipcode))),'n')
if(nchar(input$zipcode)>5)
{
updateTextInput(session,'zipcode',value=substr(input$zipcode,1,5))
showModal(modalDialog(
title = "Error!",
"Character limit exceeded!",
easyClose = TRUE
))
}
if(is.na(as.numeric(input$zipcode)))
{
showModal(modalDialog(
title = "Error!",
"Shoud be a digit",
easyClose = TRUE
))
}
}
)
}
)
shinyApp(ui=ui,server)

Regex应该做到这一点。这只是检查是否有任何东西不是数字:

grepl('[^0-9]', input$zipcode)

例如

> grepl('[^0-9]', '12345')
# [1] FALSE
> grepl('[^0-9]', 'words')
# [1] TRUE
> grepl('[^0-9]', 'wordsandnumber123')
# [1] TRUE

相关内容

  • 没有找到相关文章

最新更新