
Last chance! 50% off unlimited learning
Sale ends in
renderPlot()
), you may
need to check that certain input values are available and valid before you
can render the output. validate
gives you a convenient mechanism for
doing so.
validate(..., errorClass = character(0))
need(expr, message = paste(label, "must be provided"), label)
NULL
for success,
FALSE
for silent failure, or a string for failure with an error
message.shiny-output-error-
prepended to this value.label
.
To fail with no message, use FALSE
for the message.message
is provided, but must be provided
otherwise.validate
function takes any number of (unnamed) arguments, each of
which represents a condition to test. If any of the conditions represent
failure, then a special type of error is signaled which stops execution. If
this error is not handled by application-specific code, it is displayed to
the user by Shiny.An easy way to provide arguments to validate
is to use the need
function, which takes an expression and a string; if the expression is
considered a failure, then the string will be used as the error message. The
need
function considers its expression to be a failure if it is any of
the following:
FALSE
NULL
""
FALSE
or missing values
"try-error"
actionButton
If any of these values happen to be valid, you can explicitly turn them to
logical values. For example, if you allow NA
but not NULL
, you
can use the condition !is.null(input$foo)
, because !is.null(NA)
== TRUE
.
If you need validation logic that differs significantly from need
, you
can create other validation test functions. A passing test should return
NULL
. A failing test should return an error message as a
single-element character vector, or if the failure should happen silently,
FALSE
.
Because validation failure is signaled as an error, you can use
validate
in reactive expressions, and validation failures will
automatically propagate to outputs that use the reactive expression. In
other words, if reactive expression a
needs input$x
, and two
outputs use a
(and thus depend indirectly on input$x
), it's
not necessary for the outputs to validate input$x
explicitly, as long
as a
does validate it.
## Only run examples in interactive R sessions
if (interactive()) {
ui <- fluidPage(
checkboxGroupInput('in1', 'Check some letters', choices = head(LETTERS)),
selectizeInput('in2', 'Select a state', choices = state.name),
plotOutput('plot')
)
server <- function(input, output) {
output$plot <- renderPlot({
validate(
need(input$in1, 'Check at least one letter!'),
need(input$in2 != '', 'Please choose a state.')
)
plot(1:10, main = paste(c(input$in1, input$in2), collapse = ', '))
})
}
shinyApp(ui, server)
}
Run the code above in your browser using DataLab