### Basic Shiny App Validation Setup Source: https://rstudio.github.io/shinyvalidate/articles/shinyvalidate.html This snippet demonstrates the fundamental setup for input validation in a Shiny app's server function. It includes creating an InputValidator, adding rules for required fields and email format, enabling validation feedback, and ensuring calculations only proceed with valid inputs. ```R server <- function(input, output, session) { # 1. Create an InputValidator object iv <- InputValidator$new() # 2. Add validation rules iv$add_rule("name", sv_required()) iv$add_rule("email", sv_required()) iv$add_rule("email", ~ if (!is_valid_email(.)) "Not a valid email") # 3. Start displaying errors in the UI iv$enable() output$greeting <- renderText({ # 4. Don't proceed if any input is invalid req(iv$is_valid()) paste0("Nice to meet you, ", input$name, " <", input$email, ">") }) } ``` -------------------------------- ### Basic shinyvalidate example with sv_required() Source: https://rstudio.github.io/shinyvalidate/reference/sv_required.html This example demonstrates how to set up basic validation in a Shiny application using `shinyvalidate`. It ensures the 'name' input is present and enables the validation rules. ```R if (interactive()) { library(shiny) library(shinyvalidate) ui <- fluidPage( textInput("name", "Name") ) server <- function(input, output, session) { # Validation rules are set in the server, start by # making a new instance of an `InputValidator()` iv <- InputValidator$new() # Basic usage: ensure that `input$name` is present, # and return a terse validation message if not iv$add_rule("name", sv_required()) # Finally, `enable()` the validation rules iv$enable() } shinyApp(ui, server) } ``` -------------------------------- ### Install shinyvalidate from GitHub Source: https://rstudio.github.io/shinyvalidate/index.html Install the development version of shinyvalidate directly from its GitHub repository using the remotes package. ```r remotes::install_github("rstudio/shinyvalidate") ``` -------------------------------- ### Implement sv_lt() in a Shiny application Source: https://rstudio.github.io/shinyvalidate/reference/sv_lt.html Example demonstrating how to initialize an InputValidator and apply the sv_lt rule to a text input field. ```R ## Only run examples in interactive R sessions if (interactive()) { library(shiny) library(shinyvalidate) ui <- fluidPage( textInput("number", "Number") ) server <- function(input, output, session) { # Validation rules are set in the server, start by # making a new instance of an `InputValidator()` iv <- InputValidator$new() # Basic usage: `sv_lt()` requires a value # to compare against the field value; a message # will be shown if the validation of # `input$number` fails iv$add_rule("number", sv_lt(10)) # Finally, `enable()` the validation rules iv$enable() } shinyApp(ui, server) } ``` -------------------------------- ### Shiny App with URL Validation Source: https://rstudio.github.io/shinyvalidate/reference/sv_url.html This example demonstrates how to integrate sv_url() into a Shiny app to validate a text input field for URLs. Ensure shiny and shinyvalidate are installed and loaded. ```R if (interactive()) { library(shiny) library(shinyvalidate) ui <- fluidPage( textInput("url", "URL") ) server <- function(input, output, session) { # Validation rules are set in the server, start by # making a new instance of an `InputValidator()` iv <- InputValidator$new() # Basic usage: `sv_url()` works well with its # defaults; a message will be displayed if the # validation of `input$address` fails iv$add_rule("url", sv_url()) # Finally, `enable()` the validation rules iv$enable() } shinyApp(ui, server) } ``` -------------------------------- ### Complete module implementation with custom validation Source: https://rstudio.github.io/shinyvalidate/articles/advanced.html A full example showing the UI and server components of a password module that supports caller-defined validation rules. ```R library(shiny) library(shinyvalidate) #' A Shiny module UI function that pairs with password_input(). #' #' @param id Module instance ID. The same value must be passed to the matching #' password_input() call. #' @param value The default value. password_input_ui <- function(id, value = NULL) { ns <- NS(id) tagList( passwordInput(ns("pw1"), "Password", value = value), passwordInput(ns("pw2"), "Password (confirm)", value = value) ) } #' A Shiny module server function that pairs with password_input_ui(). #' #' Includes #' #' @param id Module instance ID. The same value must be passed to the matching #' password_input_ui() call. #' @param required If `TRUE` (the default), the returned validator will include #' a rule that ensures a password is provided. #' @param password_rule Optional validation function or formula that can impose #' further validation rules on the password. Like all validation functions and #' formulas, the return value should be either a string describing an error, #' or `NULL` if the input value is acceptable. password_input <- function(id, required = TRUE, password_rule = NULL) { moduleServer(id, function(input, output, session) { iv <- InputValidator$new() if (isTRUE(required)) { iv$add_rule("pw1", sv_required()) } iv$add_rule("pw2", ~ if (!identical(., input$pw1)) "Passwords do not match") # Add custom rule passed in by caller if (!is.null(password_rule)) { iv$add_rule("pw1", password_rule) } list( value = reactive({ if (iv$is_valid()) { input$pw1 } }), reset = function() { updateTextInput(session, "pw1", value = "") updateTextInput(session, "pw2", value = "") }, iv = iv ) }) } ui <- fluidPage( password_input_ui("password"), actionButton("continue", "Continue") ) server <- function(input, output, session) { # Initialize the module, passing custom validation logic via password_rule ``` -------------------------------- ### Install shinyvalidate from CRAN Source: https://rstudio.github.io/shinyvalidate/index.html Use this command to install the latest stable release of the shinyvalidate package from CRAN. ```r install.packages("shinyvalidate") ``` -------------------------------- ### Implement range validation in a Shiny app Source: https://rstudio.github.io/shinyvalidate/reference/sv_between.html A complete example demonstrating how to initialize an InputValidator and apply the sv_between rule to a text input. ```R ## Only run examples in interactive R sessions if (interactive()) { library(shiny) library(shinyvalidate) ui <- fluidPage( textInput("count", "Count") ) server <- function(input, output, session) { # Validation rules are set in the server, start by # making a new instance of an `InputValidator()` iv <- InputValidator$new() # Basic usage: `sv_between()` requires `left` and # `right` boundary values; a message will be # displayed if the validation of `input$count` fails iv$add_rule("count", sv_between(10, 100)) # Finally, `enable()` the validation rules iv$enable() } shinyApp(ui, server) } ``` -------------------------------- ### Implement composite rules in a Shiny app Source: https://rstudio.github.io/shinyvalidate/reference/compose_rules.html Full example demonstrating the integration of composite rules within a Shiny application's server logic. ```R # Use the `positive_even_integer()` rule function # to check that a supplied value is an integer, greater # than zero, and even (in that order) ## Only run examples in interactive R sessions if (interactive()) { library(shiny) library(shinyvalidate) ui <- fluidPage( textInput("value", "Value") ) server <- function(input, output, session) { # Validation rules are set in the server, start by # making a new instance of an `InputValidator()` iv <- InputValidator$new() # Add two `add_rule()` statements: one that # combines `sv_required()` and `sv_numeric()` in # single rule, and another that is defined # through the use of `compose_rules()` iv$add_rule("value", compose_rules(sv_required(), sv_numeric())) iv$add_rule("value", positive_even_integer()) # Finally, `enable()` the validation rules iv$enable() } shinyApp(ui, server) } ``` -------------------------------- ### Implement sv_not_equal in a Shiny application Source: https://rstudio.github.io/shinyvalidate/reference/sv_not_equal.html Example demonstrating how to add the sv_not_equal rule to an InputValidator instance within a Shiny server function. ```R ## Only run examples in interactive R sessions if (interactive()) { library(shiny) library(shinyvalidate) ui <- fluidPage( textInput("score", "Number") ) server <- function(input, output, session) { # Validation rules are set in the server, start by # making a new instance of an `InputValidator()` iv <- InputValidator$new() # Basic usage: `sv_not_equal()` requires a value # to compare against the field value; a message # will be shown if the validation of # `input$score` fails iv$add_rule("score", sv_not_equal(0)) # Finally, `enable()` the validation rules iv$enable() } shinyApp(ui, server) } ``` -------------------------------- ### Enable Input Validation Source: https://rstudio.github.io/shinyvalidate/reference/InputValidator.html Starts displaying validation feedback in the UI. Safe to call on already-enabled validators. ```R InputValidator$enable() ``` -------------------------------- ### Implement sv_lte in a Shiny application Source: https://rstudio.github.io/shinyvalidate/reference/sv_lte.html Example demonstrating how to add an sv_lte validation rule to an InputValidator instance within a Shiny server function. ```R ## Only run examples in interactive R sessions if (interactive()) { library(shiny) library(shinyvalidate) ui <- fluidPage( textInput("number", "Number") ) server <- function(input, output, session) { # Validation rules are set in the server, start by # making a new instance of an `InputValidator()` iv <- InputValidator$new() # Basic usage: `sv_lte()` requires a value # to compare against the field value; a message # will be shown if the validation of # `input$number` fails iv$add_rule("number", sv_lte(0)) # Finally, `enable()` the validation rules iv$enable() } shinyApp(ui, server) } ``` -------------------------------- ### Compose custom validation rules Source: https://rstudio.github.io/shinyvalidate/reference/compose_rules.html Example showing how to create a composite rule function using built-in shinyvalidate rules and a custom formula. ```R # Create a new shinyvalidate rule that is composed # of two `sv_*()` rule functions (`sv_integer()` and # `sv_gt()`, and a custom function for ensuring # a number is even) positive_even_integer <- function() { compose_rules( sv_integer(), sv_gt(0), ~ if (. %% 2 == 1) "Must be an even number" ) } ``` -------------------------------- ### Implement email validation in a Shiny app Source: https://rstudio.github.io/shinyvalidate/reference/sv_email.html This example demonstrates how to integrate sv_email() into a Shiny application using InputValidator. Ensure validation rules are enabled before use. ```R if (interactive()) { library(shiny) library(shinyvalidate) ui <- fluidPage( textInput("email", "Email") ) server <- function(input, output, session) { # Validation rules are set in the server, start by # making a new instance of an `InputValidator()` iv <- InputValidator$new() # Basic usage: `sv_email()` works well with its # defaults; a message will be displayed if the # validation of `input$email` fails iv$add_rule("email", sv_email()) # Finally, `enable()` the validation rules iv$enable() } shinyApp(ui, server) } ``` -------------------------------- ### Basic sv_equal() usage in Shiny app Source: https://rstudio.github.io/shinyvalidate/reference/sv_equal.html This example demonstrates how to use sv_equal() within a Shiny application to validate a text input. Ensure the 'shiny' and 'shinyvalidate' libraries are loaded. Validation rules are enabled using InputValidator$new() and iv$enable(). ```R if (interactive()) { library(shiny) library(shinyvalidate) ui <- fluidPage( textInput("number", "Number") ) server <- function(input, output, session) { # Validation rules are set in the server, # start by # making a new instance of an `InputValidator()` iv <- InputValidator$new() # Basic usage: `sv_equal()` requires a value # to compare against the field value; a message # will be shown if the validation of # `input$number` fails iv$add_rule("number", sv_equal(1)) # Finally, `enable()` the validation rules iv$enable() } shinyApp(ui, server) } ``` -------------------------------- ### Basic usage of sv_optional() with sv_email() Source: https://rstudio.github.io/shinyvalidate/reference/sv_optional.html This example shows how to use sv_optional() in conjunction with sv_email(). The email input is not required, but if provided, it must be a valid email format. Validation rules are enabled using iv$enable(). ```R library(shiny) library(shinyvalidate) ui <- fluidPage( textInput("email", "Email") ) server <- function(input, output, session) { # Validation rules are set in the server, start by # making a new instance of an `InputValidator()` iv <- InputValidator$new() # Basic usage: `sv_optional()` is often paired with # another `sv_*()` function; below, an email in # `input$email` is not required, but if present, it # must be valid iv$add_rule("email", sv_optional()) iv$add_rule("email", sv_email()) # Finally, `enable()` the validation rules iv$enable() } shinyApp(ui, server) ``` -------------------------------- ### Integrating sv_required() in a Shiny App Source: https://rstudio.github.io/shinyvalidate/reference/sv_required.html This example demonstrates how to use sv_required() within a Shiny application's server logic to validate a text input. ```APIDOC ## Shiny App Example with sv_required() ### Description This example shows a complete Shiny application where the 'name' input field is validated using `sv_required()` to ensure it is not empty. ### Server Logic ```R library(shiny) library(shinyvalidate) server <- function(input, output, session) { iv <- InputValidator$new() iv$add_rule("name", sv_required()) iv$enable() } ``` ### UI Definition ```R ui <- fluidPage( textInput("name", "Name") ) ``` ### App Execution ```R shinyApp(ui, server) ``` ``` -------------------------------- ### Custom test function for sv_required() Source: https://rstudio.github.io/shinyvalidate/reference/sv_required.html This example demonstrates how to change the definition of 'is present' for `sv_required()` by providing a custom `test` argument. Here, any non-NULL value will be accepted for the 'choices' input. ```R # iv$add_rule("choices", sv_required(test = is.null)) ``` -------------------------------- ### Regex Validation with Globbing Pattern Source: https://rstudio.github.io/shinyvalidate/reference/sv_regex.html An alternative usage of sv_regex where the pattern is generated using glob2rx() for wildcard matching, useful for filename validation. This example is commented out but shows how to integrate globbing. ```R # iv$add_rule( # "lookup_id", # sv_regex( # pattern = glob2rx("*.png"), # message = "A filename ending in 'png' was expected", # ignore.case = TRUE # ) # ) ``` -------------------------------- ### Basic shinyvalidate numeric input validation Source: https://rstudio.github.io/shinyvalidate/reference/sv_numeric.html This example demonstrates how to use sv_numeric() with shinyvalidate to validate a text input field. Ensure shiny and shinyvalidate libraries are loaded. Validation rules are added to an InputValidator instance and then enabled. ```R if (interactive()) { library(shiny) library(shinyvalidate) ui <- fluidPage( textInput("rating", "Rating") ) server <- function(input, output, session) { # Validation rules are set in the server, start by # making a new instance of an `InputValidator()` iv <- InputValidator$new() # Basic usage: `sv_numeric()` works well with its # defaults; a message will be displayed if the # validation of `input$rating` fails iv$add_rule("rating", sv_numeric()) # Finally, `enable()` the validation rules iv$enable() } shinyApp(ui, server) } ``` -------------------------------- ### Initialize Shiny and Shinyvalidate Source: https://rstudio.github.io/shinyvalidate/articles/advanced.html Load the necessary libraries, shiny and shinyvalidate, to begin building your Shiny application with input validation capabilities. ```R library(shiny) library(shinyvalidate) ``` -------------------------------- ### InputValidator$condition() Source: https://rstudio.github.io/shinyvalidate/reference/InputValidator.html Sets or gets a condition that determines if validation rules should be executed. ```APIDOC ## InputValidator$condition() ### Description Gets or sets a condition that overrides all of the rules in this validator. If the condition returns FALSE, validation rules are skipped. ### Parameters - **cond** (function/formula/NULL) - Optional - A function or formula returning TRUE/FALSE. ``` -------------------------------- ### sv_lte() Function Documentation Source: https://rstudio.github.io/shinyvalidate/reference/sv_lte.html Documentation for the sv_lte() function, including its arguments, return value, and related functions. ```APIDOC ## sv_lte() ### Description Validate that a field is less than or equal to a specified value. The `sv_lte()` function compares the field value to a specified value with the `<=` operator. ### Arguments * **rhs** (any) - The right hand side (RHS) value is to be used for the comparison with the field value. The validation check will effectively be of the form ` <= `. * **message_fmt** (character) - The validation error message to use if the field fails the validation test. Use the `{rhs}` string parameter to customize the message, including what was set in `rhs`. While the default message uses this string parameter, it is not required in a user-defined `message_fmt` string. * **allow_multiple** (logical) - If `FALSE` (the default), then the length of the input vector must be exactly one; if `TRUE`, then any length is allowed (including a length of zero; use `sv_required()` if one or more values should be required). * **allow_na** (logical) - If `FALSE` (the default), then any `NA` element will cause validation to fail. * **allow_nan** (logical) - If `FALSE` (the default), then any `NaN` element will cause validation to fail. * **allow_inf** (logical) - If `FALSE` (the default), then any `Inf` or `-Inf` element will cause validation to fail. ### Value A function suitable for use as an `InputValidator$add_rule()` rule. ### See also The other comparison-based rule functions: `sv_gt()`, `sv_gte()`, `sv_lt()`, `sv_equal()`, and `sv_not_equal()`. The `sv_lt()` function may be needed if the field value should not pass validation when it is equal to the comparison value. Other rule functions: `compose_rules()`, `sv_between()`, `sv_email()`, `sv_equal()`, `sv_gte()`, `sv_gt()`, `sv_in_set()`, `sv_integer()`, `sv_lt()`, `sv_not_equal()`, `sv_numeric()`, `sv_optional()`, `sv_regex()`, `sv_required()`, `sv_url()` ### Examples ```r # Only run examples in interactive R sessions if (interactive()) { library(shiny) library(shinyvalidate) ui <- fluidPage( textInput("number", "Number") ) server <- function(input, output, session) { # Validation rules are set in the server, start by # making a new instance of an `InputValidator()` iv <- InputValidator$new() # Basic usage: `sv_lte()` requires a value # to compare against the field value; a message # will be shown if the validation of # `input$number` fails iv$add_rule("number", sv_lte(0)) # Finally, `enable()` the validation rules iv$enable() } shinyApp(ui, server) } ``` ``` -------------------------------- ### Recommended: Passing validation rules as parameters Source: https://rstudio.github.io/shinyvalidate/articles/advanced.html Encapsulate validation logic by accepting a rule function as an argument in the module server function. ```R password_input <- function(id, password_rule = NULL) { moduleServer(id, function(input, output, session) { iv <- InputValidator$new() iv$add_rule("pw1", sv_required()) iv$add_rule("pw2", sv_required()) iv$add_rule("pw2", ~ if (!identical(., input$pw1)) "Passwords do not match") # Add custom rule passed in by caller if (!is.null(password_rule)) { iv$add_rule("pw1", password_rule) } }) } server <- function(input, output, session) { # Initialize the module, passing custom validation logic via password_rule password_result <- password_input("password", password_rule = function(pw) { if (!grepl("[0-9]", pw) || !grepl("[A-Z]", pw)) { "Must include a number and an upper-case character" } else if (nchar(pw) < 8) { "Must be at least 8 characters" } }) } ``` -------------------------------- ### Initialize InputValidator Source: https://rstudio.github.io/shinyvalidate/reference/InputValidator.html Creates a new validator instance. The priority parameter determines the execution order of the internal observer relative to other observers. ```R InputValidator$new( priority = 1000, session = shiny::getDefaultReactiveDomain() ) ``` -------------------------------- ### InputValidator Object Creation and Usage Source: https://rstudio.github.io/shinyvalidate/reference/index.html Demonstrates how to create and manage InputValidator objects for adding real-time validation rules to Shiny inputs. ```APIDOC ## InputValidator Object ### Description The `InputValidator` R6 class is used to add real-time input validation to Shiny applications. Multiple `InputValidator` instances can be created for independent forms. ### Methods - `InputValidator$new()`: Creates a new InputValidator object. - `InputValidator$add_rule(inputId, rule)`: Adds a validation rule for a specific input field. - `input_provided()`: Checks if an input value has been provided. - `skip_validation()`: Skips normal validation performed by a rule. ### Example Usage ```R library(shiny) library(shinyvalidate) ui <- fluidPage( textInput("name", "Name:"), numericInput("age", "Age:", value = 20), actionButton("submit", "Submit") ) server <- function(input, output, session) { iv <- InputValidator$new() iv$add_rule("name", sv_required("Please enter your name.")) iv$add_rule("age", sv_numeric("Age must be a number.")) iv$add_rule("age", sv_gt(0, "Age must be positive.")) observeEvent(input$submit, { if (iv$is_valid()) { # Proceed with form submission showNotification("Form submitted successfully!") } else { # Validation failed, messages are shown automatically } }) } shinyApp(ui, server) ``` ``` -------------------------------- ### sv_equal() Function Documentation Source: https://rstudio.github.io/shinyvalidate/reference/sv_equal.html Details on the sv_equal() function, its arguments, return value, and usage within shinyvalidate. ```APIDOC ## sv_equal() ### Description The `sv_equal()` function compares the field value to a specified value with the `==` operator. ### Arguments - **rhs** (any) - The right hand side (RHS) value is to be used for the comparison with the field value. The validation check will effectively be of the form ` == `. - **message_fmt** (string) - The validation error message to use if the field fails the validation test. Use the `"{rhs}"` string parameter to customize the message, including what was set in `rhs`. While the default message uses this string parameter, it is not required in a user-defined `message_fmt` string. - **allow_multiple** (boolean) - If `FALSE` (the default), then the length of the input vector must be exactly one; if `TRUE`, then any length is allowed (including a length of zero; use `sv_required()` if one or more values should be required). - **allow_na** (boolean) - If `FALSE` (the default), then any `NA` element will cause validation to fail. - **allow_nan** (boolean) - If `FALSE` (the default), then any `NaN` element will cause validation to fail. - **allow_inf** (boolean) - If `FALSE` (the default), then any `Inf` or `-Inf` element will cause validation to fail. ### Value A function suitable for use as an `InputValidator$add_rule()` rule. ### See also The other comparison-based rule functions: `sv_gt()`, `sv_gte()`, `sv_lt()`, `sv_lte()`, and `sv_not_equal()` (which serves as the opposite function to `sv_equal()`). Other rule functions: `compose_rules()`, `sv_between()`, `sv_email()`, `sv_gte()`, `sv_gt()`, `sv_in_set()`, `sv_integer()`, `sv_lte()`, `sv_lt()`, `sv_not_equal()`, `sv_numeric()`, `sv_optional()`, `sv_regex()`, `sv_required()`, `sv_url()` ### Examples ```R ## Only run examples in interactive R sessions if (interactive()) { library(shiny) library(shinyvalidate) ui <- fluidPage( textInput("number", "Number") ) server <- function(input, output, session) { # Validation rules are set in the server, start by # making a new instance of an `InputValidator()` iv <- InputValidator$new() # Basic usage: `sv_equal()` requires a value # to compare against the field value; a message # will be shown if the validation of # `input$number` fails iv$add_rule("number", sv_equal(1)) # Finally, `enable()` the validation rules iv$enable() } shinyApp(ui, server) } ``` ``` -------------------------------- ### Shiny Text Input HTML with Validation Error Source: https://rstudio.github.io/shinyvalidate/articles/displaying.html An example of the HTML structure for a Shiny text input after a validation error has occurred. The 'has-error' class is added to the 'form-group', and a 'help-block' span displays the error message. ```html
Required
``` -------------------------------- ### Basic Shiny App with shinyvalidate Source: https://rstudio.github.io/shinyvalidate/index.html A simple Shiny application demonstrating the basic usage of shinyvalidate. It includes creating an InputValidator object, adding required and email validation rules, and enabling the validator. ```r library(shiny) library(shinyvalidate) ui <- fluidPage( textInput("name", "Name"), textInput("email", "Email") ) server <- function(input, output, session) { iv <- InputValidator$new() iv$add_rule("name", sv_required()) iv$add_rule("email", sv_required()) iv$add_rule("email", sv_email()) iv$enable() } shinyApp(ui, server) ``` -------------------------------- ### Basic Input Validation with sv_regex Source: https://rstudio.github.io/shinyvalidate/reference/sv_regex.html Demonstrates how to use sv_regex to validate a text input field for alphanumeric characters. Ensure shiny and shinyvalidate libraries are loaded and InputValidator is enabled. ```R library(shiny) library(shinyvalidate) ui <- fluidPage( textInput("lookup_id", "Lookup ID") ) server <- function(input, output, session) { # Validation rules are set in the server, start by # making a new instance of an `InputValidator()` iv <- InputValidator$new() # Basic usage: `sv_regex()` requires both a regex # pattern and message to display if the validation # of `input$lookup_id` fails iv$add_rule( "lookup_id", sv_regex("^[a-zA-Z0-9]*$", "Only alphanumeric characters allowed") ) # Finally, `enable()` the validation rules iv$enable() } shinyApp(ui, server) ``` -------------------------------- ### Anti-pattern: External access to module input IDs Source: https://rstudio.github.io/shinyvalidate/articles/advanced.html This approach violates module boundaries by requiring the caller to know internal input IDs. Avoid this implementation. ```R server <- function(input, output, session) { password_result <- password_input("password") # Adding a rule for one of password_input's inputs, from outside # of password_input. DON'T DO THIS! password_result$iv$add_rule(NS("password", "pw1"), ~ { # Custom validation logic if (!grepl("[0-9]", pw) || !grepl("[A-Z]", pw)) { "Must include a number and an upper-case character" } else if (nchar(pw) < 8) { "Must be at least 8 characters" } }) } ``` -------------------------------- ### Retrieve Input Fields Source: https://rstudio.github.io/shinyvalidate/reference/InputValidator.html Returns the status of input validation rules. ```R InputValidator$fields() ``` -------------------------------- ### Basic Usage of sv_in_set() in Shiny App Source: https://rstudio.github.io/shinyvalidate/reference/sv_in_set.html Demonstrates the basic usage of `sv_in_set()` within a Shiny application. It sets up a text input and adds a validation rule to ensure the input is one of the numbers from 1 to 5. Validation is enabled using `iv$enable()`. ```R if (interactive()) { library(shiny) library(shinyvalidate) ui <- fluidPage( textInput("rating", "Rating") ) server <- function(input, output, session) { # Validation rules are set in the server, start by # making a new instance of an `InputValidator()` iv <- InputValidator$new() # Basic usage: `sv_in_set()` requires a value # set given as a vector; a message will be # shown if the validation of `input$rating` fails iv$add_rule("rating", sv_in_set(1:5)) # Finally, `enable()` the validation rules iv$enable() } shinyApp(ui, server) } ``` -------------------------------- ### Enable Validation Feedback Source: https://rstudio.github.io/shinyvalidate/articles/shinyvalidate.html Call `iv$enable()` to activate validation messages. Once enabled, messages update reactively as input values change. This is typically called once. ```r iv$enable() ``` -------------------------------- ### Define compose_rules signature Source: https://rstudio.github.io/shinyvalidate/reference/compose_rules.html The basic syntax for the compose_rules function. ```R compose_rules(...) ``` -------------------------------- ### Run Manual Validation Source: https://rstudio.github.io/shinyvalidate/reference/InputValidator.html Executes validation rules and returns a named list of results. Intended for advanced use cases. ```R InputValidator$validate() ``` -------------------------------- ### Create an optional input rule Source: https://rstudio.github.io/shinyvalidate/reference/sv_optional.html Use sv_optional() to create a validation function that marks an input as optional. If the input is not provided, other rules for this input are skipped. Otherwise, the rule passes. ```R sv_optional(test = input_provided) ``` -------------------------------- ### input_provided Function Source: https://rstudio.github.io/shinyvalidate/reference/input_provided.html Checks if an input value has been provided. This function is based on shiny::isTruthy() but with a different treatment of FALSE values. ```APIDOC ## input_provided(val) ### Description Checks whether an input value has been provided. This function takes an input value and uses heuristics to guess whether it represents an "empty" input vs. one that the user has provided. This will vary by input type; for example, a `shiny::textInput()` is `""` when empty, while a `shiny::numericInput()` is `NA`. `input_provided` returns `TRUE` for all values except: * `NULL` * `""` * An empty atomic vector or list * An atomic vector that contains only missing (`NA`) values * A character vector that contains only missing and/or `""` values * An object of class `"try-error"` * A value that represents an unclicked `shiny::actionButton()` ### Arguments * **val** (any) - Values to test for availability in a Shiny context. ### Value A logical vector of length 1. ### Details This function is based on `shiny::isTruthy()` but tweaked here in shinyvalidate to change the treatment of `FALSE` values: `isTruthy(FALSE)` returns `FALSE`, but `input_provided(FALSE)` returns `TRUE`. This difference is motivated by `shiny::checkboxInput()`, where `isTruthy()` answers the question of "is the input present _and checked_ " while `input_provided` is just "is the input present". ``` -------------------------------- ### Apply Conditional Validation Rule Source: https://rstudio.github.io/shinyvalidate/articles/advanced.html Shows three equivalent ways to apply a condition to an InputValidator object. Validation rules are only observed when the condition evaluates to TRUE. If the condition becomes FALSE, existing errors are dismissed. ```R iv$condition(~ isTRUE(input$filter_by_date)) ``` ```R iv$condition(function() { isTRUE(input$filter_by_date) }) ``` ```R filtering_by_date <- reactive({ isTRUE(input$filter_by_date) }) iv$condition(filtering_by_date) ``` -------------------------------- ### InputValidator$new() Source: https://rstudio.github.io/shinyvalidate/reference/InputValidator.html Creates a new instance of the InputValidator object. ```APIDOC ## InputValidator$new() ### Description Create a new validator object. ### Parameters - **priority** (numeric) - Optional - Priority of the internal observer. Defaults to 1000. - **session** (Shiny session) - Optional - The Shiny session object. ``` -------------------------------- ### Create a URL validation rule Source: https://rstudio.github.io/shinyvalidate/reference/sv_url.html Use sv_url() to create a validation rule that checks if an input value is a valid URL. Customize the error message, and control whether multiple values or NA values are allowed. ```R sv_url(message = "Not a valid URL", allow_multiple = FALSE, allow_na = FALSE) ``` -------------------------------- ### Custom Validation Rule using Formula Source: https://rstudio.github.io/shinyvalidate/articles/shinyvalidate.html Implement custom validation logic by providing a formula to `add_rule()`. The formula should test the input value (represented by '.') and return `NULL` for valid input or a character string describing the error. ```R iv$add_rule("email", ~ if (!is_valid_email(.)) "Not a valid email") ``` -------------------------------- ### Conditionally Execute Action Based on Validity Source: https://rstudio.github.io/shinyvalidate/articles/shinyvalidate.html Use `iv$is_valid()` within an `observeEvent` to conditionally execute code only when all inputs are valid. Displays a notification if validation fails. ```r observeEvent(input$continue, { if (iv$is_valid()) { # use inputs... } else { showNotification( "Please fix the errors in the form before continuing", type = "warning" ) } }) ``` -------------------------------- ### Basic Shiny App with sv_integer() Validation Source: https://rstudio.github.io/shinyvalidate/reference/sv_integer.html Demonstrates basic usage of sv_integer() in a Shiny application. It adds a rule to validate the 'count' text input, displaying a message if the input is not an integer. Ensure the app is run interactively. ```R if (interactive()) { library(shiny) library(shinyvalidate) ui <- fluidPage( textInput("count", "Count") ) server <- function(input, output, session) { # Validation rules are set in the server, start by # making a new instance of an `InputValidator()` iv <- InputValidator$new() # Basic usage: `sv_integer()` works well with its # defaults; a message will be displayed if the # validation of `input$count` fails iv$add_rule("count", sv_integer()) # Finally, `enable()` the validation rules iv$enable() } shinyApp(ui, server) } ``` -------------------------------- ### sv_integer() Rule Configuration Source: https://rstudio.github.io/shinyvalidate/reference/sv_integer.html Configure the sv_integer() rule with custom messages and options for allowing multiple values, NA, or NaN. Defaults to disallowing multiple values, NA, and NaN. ```R sv_integer( message = "An integer is required", allow_multiple = FALSE, allow_na = FALSE, allow_nan = FALSE ) ``` -------------------------------- ### Guard Reactive Calculation with Validity Check Source: https://rstudio.github.io/shinyvalidate/articles/shinyvalidate.html Use `req(iv$is_valid())` at the beginning of a reactive expression to ensure it only executes when inputs are valid. Silently aborts execution if validation fails. ```r df <- reactive({ req(iv$is_valid()) # use inputs... }) ``` -------------------------------- ### Widget-level Support: Input Binding Customization Source: https://rstudio.github.io/shinyvalidate/articles/displaying.html Custom input widgets can define their own behavior for displaying validation errors by implementing `setInvalid` and `clearInvalid` methods on their JavaScript `InputBinding` objects. ```APIDOC ## InputBinding Customization ### Description Implement `setInvalid(el, data)` and `clearInvalid(el)` on your JavaScript `InputBinding` to control how validation errors are displayed for custom input widgets. ### Methods #### `binding.setInvalid(el, data)` - **el** (HTMLElement) - The HTML element of the input. - **data** (object) - Contains validation error information. - **data.type** (string) - Currently "error", may include "warning" and "info" in the future. - **data.message** (string) - The validation error message. ### `binding.clearInvalid(el)` - **el** (HTMLElement) - The HTML element of the input. ### Notes - `shinyvalidate` may call these methods in arbitrary order and multiple times. - Both methods must handle inputs in "normal" or "error" states. ### Request Example (Conceptual) ```javascript // Example of implementing setInvalid myInputBinding.setInvalid = function(el, data) { // Display error message and apply CSS changes console.log('Setting invalid:', data.message); $(el).addClass('invalid-input'); // ... add error message display logic ... }; // Example of implementing clearInvalid myInputBinding.clearInvalid = function(el) { // Remove error message and revert CSS changes console.log('Clearing invalid'); $(el).removeClass('invalid-input'); // ... remove error message display logic ... }; ``` ### Response Example (Conceptual) No direct response, but UI updates are expected. ``` -------------------------------- ### Add Validation Rule with Named Function and Arguments Source: https://rstudio.github.io/shinyvalidate/articles/shinyvalidate.html Use a named function for validation, passing additional arguments via `...` to `iv$add_rule()`. This allows for more complex validation logic with configurable parameters. ```r not_greater_than <- function(value, limit, message = "Value is too high") { if (value > limit) message } iv$add_rule("samples", not_greater_than, limit = nrow(df), message = "Sample count cannot exceed number of rows" ) ``` -------------------------------- ### Optional Field Validation with Custom Rule Source: https://rstudio.github.io/shinyvalidate/articles/shinyvalidate.html This demonstrates how to handle optional fields where validation should only occur if a value is provided. `sv_optional()` skips subsequent rules if the input is empty, and a custom formula checks the format if a value is present. ```R iv$add_rule("email", sv_optional()) iv$add_rule("email", ~ if (!is_valid_email(.)) "Invalid email address") ``` -------------------------------- ### InputValidator Methods Source: https://rstudio.github.io/shinyvalidate/reference/InputValidator.html Methods for controlling validation feedback and checking validation status. ```APIDOC ## InputValidator$enable() ### Description Begin displaying input validation feedback in the user interface. Once enabled, this validator object will automatically keep the feedback up-to-date. ## InputValidator$disable() ### Description Clear existing input validation feedback in the user interface for all inputs represented in this validator's ruleset, and stop providing feedback going forward. ## InputValidator$is_valid() ### Description Returns TRUE if all input validation rules currently pass, FALSE if not. ## InputValidator$validate() ### Description Run validation rules and gather results. Returns a named list where names are input IDs and values are NULL (if passing) or a character vector describing the validation problem. ``` -------------------------------- ### Basic sv_gte() usage in Shiny app Source: https://rstudio.github.io/shinyvalidate/reference/sv_gte.html Integrate sv_gte() into a Shiny application to validate a text input. Ensure the InputValidator is enabled after adding the rule. ```R if (interactive()) { library(shiny) library(shinyvalidate) ui <- fluidPage( textInput("number", "Number") ) server <- function(input, output, session) { # Validation rules are set in the server, start by # making a new instance of an `InputValidator()` iv <- InputValidator$new() # Basic usage: `sv_gte()` requires a value # to compare against the field value; a message # will be shown if the validation of # `input$number` fails iv$add_rule("number", sv_gte(1)) # Finally, `enable()` the validation rules iv$enable() } shinyApp(ui, server) } ``` -------------------------------- ### Define sv_equal rule Source: https://rstudio.github.io/shinyvalidate/reference/sv_equal.html Use sv_equal() to create a validation rule that checks if an input field's value is equal to a specified value. Customize the error message and control the handling of multiple values, NA, NaN, and Inf. ```R sv_equal( rhs, message_fmt = "Must be equal to {rhs}.", allow_multiple = FALSE, allow_na = FALSE, allow_nan = FALSE, allow_inf = FALSE ) ``` -------------------------------- ### Create an email validation rule Source: https://rstudio.github.io/shinyvalidate/reference/sv_email.html Use sv_email() to create a validation rule that checks if an input value is a valid email address. Customize the error message and rules for multiple or NA values. ```R sv_email( message = "Not a valid email address", allow_multiple = FALSE, allow_na = FALSE ) ``` -------------------------------- ### Add Child Validator to Parent Source: https://rstudio.github.io/shinyvalidate/articles/advanced.html Demonstrates how to add one InputValidator object as a child to another. This allows for hierarchical validation structures where the parent validator's validity depends on its children. ```R parent_iv$add_validator(child_iv) ``` -------------------------------- ### sv_optional() Function Source: https://rstudio.github.io/shinyvalidate/reference/sv_optional.html The sv_optional() function creates a validation rule that marks an input as optional. If the input is not provided, subsequent rules are skipped, and the input is considered valid. It never returns a validation error itself. ```APIDOC ## sv_optional() ### Description Indicates that an input is allowed to not be present. If an `sv_optional()` rule sees that an input is not present, subsequent rules for that input are skipped and the input is considered valid. Otherwise, the rule simply passes. (`sv_optional()` will never return a validation error/message.) ### Arguments * **test** (function or formula) - A single-argument function or single-sided formula (using `.` to access the value to test) that returns `TRUE` for success and `FALSE` for failure. Defaults to `input_provided()`. ### Value A function suitable for use as an `InputValidator$add_rule()` rule. ### See also * `sv_required()`: The inverse of `sv_optional()`. * `compose_rules()`: For combining multiple rules. * Other rule functions: `sv_between()`, `sv_email()`, `sv_equal()`, `sv_gte()`, `sv_gt()`, `sv_in_set()`, `sv_integer()`, `sv_lte()`, `sv_lt()`, `sv_not_equal()`, `sv_numeric()`, `sv_regex()`, `sv_required()`, `sv_url()` ### Examples ```R if (interactive()) { library(shiny) library(shinyvalidate) ui <- fluidPage( textInput("email", "Email") ) server <- function(input, output, session) { iv <- InputValidator$new() iv$add_rule("email", sv_optional()) iv$add_rule("email", sv_email()) iv$enable() } shinyApp(ui, server) } ``` ``` -------------------------------- ### Define sv_gte() rule Source: https://rstudio.github.io/shinyvalidate/reference/sv_gte.html Use sv_gte() to create a validation rule that checks if an input value is greater than or equal to a specified number. Customize the error message using message_fmt. ```R sv_gte( rhs, message_fmt = "Must be greater than or equal to {rhs}.", ``` -------------------------------- ### Internal Validation Implementation Source: https://rstudio.github.io/shinyvalidate/reference/InputValidator.html Internal method for validation logic. ```R InputValidator$_validate_impl(indent) ``` -------------------------------- ### sv_not_equal() Rule Source: https://rstudio.github.io/shinyvalidate/reference/sv_not_equal.html This snippet demonstrates how to use the sv_not_equal() function to add a validation rule to an InputValidator instance. The rule ensures that the input field 'score' is not equal to 0. ```APIDOC ## POST /api/users ### Description This endpoint allows for the creation of new user accounts. ### Method POST ### Endpoint /api/users ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of users to return. #### Request Body - **username** (string) - Required - The desired username for the new account. - **email** (string) - Required - The email address for the new account. - **password** (string) - Required - The password for the new account. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com", "password": "securepassword123" } ``` ### Response #### Success Response (200) - **userId** (string) - The unique identifier for the newly created user. - **message** (string) - A confirmation message indicating successful user creation. #### Response Example ```json { "userId": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "message": "User account created successfully." } ``` ``` -------------------------------- ### Generate Shiny Text Input HTML Source: https://rstudio.github.io/shinyvalidate/articles/displaying.html This R code generates the HTML for a standard Shiny text input. It's useful for understanding the default structure that shinyvalidate targets for error display. ```r cat(as.character(shiny::textInput("email", "Email address"))) ``` -------------------------------- ### Configure validation condition Source: https://rstudio.github.io/shinyvalidate/reference/InputValidator.html Sets a condition that must be met for the validator to execute its rules. If the condition returns FALSE, all rules are treated as passing. ```R InputValidator$condition(cond) ``` -------------------------------- ### sv_regex Function Signature Source: https://rstudio.github.io/shinyvalidate/reference/sv_regex.html Defines the signature and arguments for the sv_regex validation function. It takes a regex pattern, an error message, and several optional arguments passed to base::grepl(). ```R sv_regex( pattern, message, ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE, invert = FALSE ) ```