Hello. I'm a bit new to shiny validate, but it seems really great. My code asks the user to first state how many treatments there are (input$in1) and then displays that many textInput fields for the names of the treatments (using a string name for the input ids)
Is there a way to validate these fields as the user enters the names? My attempt at a reprex is below.
if (interactive()) {
library(shiny)
library(shinyjs)
library(shinyvalidate)
ui <- fluidPage(
numericInput('in1', 'Enter the number of treatments between 2 and 6', value = 2),
shinyjs::hidden(div(id = "treatmentNamesID",
uiOutput("treatmentNamesInput")
)),
verbatimTextOutput("theTreatmentNames")
)
server <- function(input, output) {
iv_in1 <- InputValidator$new()
iv_in1$add_rule("in1", sv_required())
iv_in1$add_rule("in1", ~ if (!((input$in1 >= 2 ) && (input$in1 <= 6))) "Not between two and 6")
iv_in1$add_rule("in1", ~ if (!is.integer(input$in1)) "Not an integer")
iv_in1$enable()
observeEvent(input$in1,{
shinyjs::showElement(id = "treatmentNamesID")
})
observeEvent(input$printButton, {
req(iv_in1$is_valid())
TrtNames = c()
for (i in 1:input$in1) {
fname = paste0("TrtNames", i)
TrtNames = c(TrtNames,input[[fname]])
}
output$theTreatmentNames = renderPrint({
print(TrtNames)
})
})
output$treatmentNamesInput <- renderUI({
req(iv_in1$is_valid())
div(id = "treatmentNamesID",
hr(),
fluidRow(
column(2, h4("Enter treatment names"))
),
fluidRow(
lapply(1:input$in1, function(i) {
fname = paste0("TrtNames", i)
column(1,
textInput(fname, label = NULL, value = paste0("T", as.character(i))
)
)
})
),
actionButton("printButton",label = "Press to print treatment names"),
br()
)
})
}
shinyApp(ui, server)
}