I would like to check if the input that the user write in the user interface is numeric and in case return a SafeError. I wrote the following code but it gives me error, could you help me?
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
textInput("price","Price:", value = "", placeholder = "00.0"),
),
mainPanel(
h5(textOutput("price")),
)))
server <- function(input, output){
output$price <- renderText(
if(input$price == "" || is.numeric(input$pirce)==FALSE)
stop(safeError("input correct price field"))
else
return(c("Price:",input$price))
)
}
shinyApp(ui = ui, server = server)
CodePudding user response:
You can maybe check using as.numeric
:
library(shiny)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
textInput("price","Price:", value = "", placeholder = "00.0"),
),
mainPanel(
h5(textOutput("price")),
)
)
)
server <- function(input, output, session){
output$price <- renderText({
check <- as.numeric(input$price)
if(is.na(check)){
stop(safeError("input correct price field"))
}else{
return(c("Price:",input$price))
}
})
}
shinyApp(ui = ui, server = server)
CodePudding user response:
input$price
is still a character until you do as.numeric(input$price)
. You can search the text using a regular expression if the pattern matches a number:
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
textInput("price", "Price:", value = "", placeholder = "00.0"),
),
mainPanel(
h5(textOutput("price")),
)
)
)
server <- function(input, output) {
output$price <- renderText(
if (!stringr::str_detect(input$price, "^[0-9] [.]?[0-9]*$")) {
stop(safeError("input correct price field"))
} else {
return(c("Price:", input$price))
}
)
}
shinyApp(ui = ui, server = server)