1

I would like to know if there was a trick to prevent users from setting the end date before the beginning date using dateRangeInput in Shiny (say the first date is "01-01-2016", the second date cannont go lower than that).

I tried by redefining the min and the max each time, but then I get stuck and cannot get my min back to its original value.

Vojtech Ruzicka
  • 16,384
  • 15
  • 63
  • 66
Captnse13
  • 11
  • 3
  • Possible duplicate of [How to prevent user from setting the end date before the start date using the Shiny dateRangeInput](https://stackoverflow.com/questions/43614708/how-to-prevent-user-from-setting-the-end-date-before-the-start-date-using-the-sh) – Scarabee Feb 27 '19 at 10:38

1 Answers1

3

Here is an example. Basically it observes changes in start date and then update the dateRangeInput object dynamically. If the previously selected end date is earlier than the new start date, then the end date is updated. The minimum possible date is also updated so that user cannot select an end date earlier than start date.

library(shiny)

ui <- shinyUI(fluidPage(

   titlePanel("Dynamically change dateRangeInput"),

   sidebarLayout(
      sidebarPanel(
        dateRangeInput("date_range", "Range of dates")
      ),

      mainPanel(
         textOutput("text")
      )
   )
))

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

  # Update the dateRangeInput if start date changes
  observeEvent(input$date_range[1], {
    end_date = input$date_range[2]
    # If end date is earlier than start date, update the end date to be the same as the new start date
    if (input$date_range[2] < input$date_range[1]) {
      end_date = input$date_range[1]
    }
    updateDateRangeInput(session,"date_range", start=input$date_range[1], end=end_date, min=input$date_range[1] )
  })

  output$text <- renderText({
    validate(
      need(input$date_range[2] >= input$date_range[1], "End date cannot be earlier than start date!")
    )
    input$date_range[2] >= input$date_range[1]
  })

})

shinyApp(ui = ui, server = server)
Xiongbing Jin
  • 11,779
  • 3
  • 47
  • 41