raistlin raistlin - 3 months ago 19
R Question

Restrict input type in shiny field

As it is,

numericInput
accepts both string and numeric inputs. If a string is entered it is converted to
NA
(try with the code below). Is there a way of not allowing the user to type a string in a numeric field in shiny?

ui <- fluidPage(
numericInput("num", label = "text not allowed", value = 1),
verbatimTextOutput("value")
)

server <- function(input, output) {
output$value <- renderPrint({ input$num })
}

shinyApp(ui = ui, server = server)


So far, I have added a text output next to the numeric input that warns the user that only numbers are accepted if she enters a string in a
numericInput
field. This solution is far from ideal for me.

I want it to be impossible for the user to enter a character value in a numeric field.

Answer

You can add validate to your expression, so only number inputs will be allowed. I'm using windows 7 64-bit with Google Chrome (IE will work too)

Note: Shiny version 0.13.2, doesn't work on Firefox.

rm(list = ls())
library(shiny)
ui <- fluidPage(
  numericInput("num", label = "text not allowed", value = 1),
  verbatimTextOutput("value")
)
server <- function(input, output) {

  numbers <- reactive({
    validate(
      need(is.numeric(input$num), "Please input a number")
    )
  })
  output$value <- renderPrint({ numbers() })      
}
shinyApp(ui = ui, server = server)
Comments