rshinynumeric-input

r shiny numericInput allows the entry of values above the max


Just checking if there is yet a solution to this issue: I don't want the user to enter values in "Input number 2" that are above the allowed max (whatever is entered in "Input number 1"). It works when the user uses the spinner, but not when the user just types the values in.

library(shiny)

ui <- fluidPage(
 numericInput(inputId = "inNumber1", label = "Input number 1", 
               value = 100, min = 10, max = 200, step = 10),
  numericInput(inputId = "inNumber2", label = "Input number 2",
               value = 50, min = 10, max = 200, step = 10),
  textOutput("out1"),
  textOutput("out2")
)

server <- function(input, output, session) {

  # Reacting to changes in input 1:
  observeEvent(input$inNumber1, {

    number1 <- input$inNumber1  # value 1
    updateNumericInput(session, inputId = "inNumber2",
                       label = "Input number 2",
                       value = floor(number1/2),
                       min = 10, max = number1, step = 10)
    output$out1 <- renderText({number1})

  })

  # Reacting to changes in input 2:
  observeEvent(input$inNumber2, {
    number2 <- input$inNumber2  # value 2
    output$out2 <- renderText({number2})
  })
}

shinyApp(ui, server)

Solution

  • One quick and dirty solution would be to through an error message, a warning or simply cap number2.

      # Reacting to changes in input 2:
      observeEvent(input$inNumber2, {
        number2 <- input$inNumber2  # value 2
        max_number2 <- 200
        if(number2 > max_number2) {
            ## Conditions
            number2 <- max_number2
        }
        output$out2 <- renderText({number2})
      })
    

    Or, for the stop conditions:

    ## Condition
    stop(paste0("number2 must be lower than ", max_number2))
    

    Or, for the warning conditions

    ## Condition
    number2 <- max_number2
    warning(paste0("number2 is set to ", max_number2))