如何确保 Shiny 中的 textInput 只接受数值?

How do I make sure my textInput in Shiny only accepts numeric values?

我不想使用 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)

正则表达式应该可以解决问题。这只是检查是否有任何东西不是数字:

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

例如,

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