Search code examples
rshinyshiny-servertextinputobservers

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

Solution

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