如何解决如何确保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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。