简体   繁体   中英

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

I don't want to use numericInput() , so is there another way to get around this? Also, I tried limiting the number of characters, the error message works, but the updateTextInput() isn't working (it was supposed to curtail the original input to only 5 characters). Any help would be appreciated!

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
        ))
      }
    }
    )
  }
)

You erroneously used input$mytext
Try:

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 should do the trick. This just checks whether anything is not a number:

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

for example,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM