Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
        ))
      }
    }
    )
  }
)
like image 518
youtube Avatar asked Nov 23 '25 18:11

youtube


1 Answers

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)
like image 148
Waldi Avatar answered Nov 26 '25 08:11

Waldi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!