!is.numeric() not working with textinput

...Good day, I'm trying to detect whenever the user enters non numeric data to some inputs and prevent it, my problem is that Im using textinputs and R is not recognizing the data as numeric , tried to convert it with as.numeric and it didn't work, with it R will detect everything as numeric even if its a string.

this is what I'm using in my code:

#textinputs for query data
textInput("Tienda","Tienda"),
    textInput("depto","depto"),
    textInput("Articulo","Articulo"),
# function in server
if(input$Tienda==""  | input$depto==""  |input$Articulo==""  ){
      shinyalert("fill every field", "fill TIENDA,DEPTO Y ARTICULO", type = "error")
    }else{
if (!is.numeric(input$depto) | !is.numeric(input$Tienda) | !is.numeric(input$Articulo)){
  shinyalert("numeric data only", "fill everything with numeric data", type = "error")
}else{
  withProgress({
    setProgress(message = "processing...")
    my_sql <- gsub("\\?DEP",trimws(input$depto),gsub("\\?STORE_NBR",trimws(input$Tienda),gsub("\\?OLD_NBR",trimws(input$Articulo),my_sql)))
    resultset<-  dataset.load(name="WM3", query=my_sql)
    #resultset <- connector.execute(name="WM3", statement=my_sql) 
    values$mydata<-resultset 
  })

any help is appreciated, thanks a lot

input$any_name is always of character class (even if you have digits in it), so your logical condition, !is.numeric(input$depto), would always be TRUE, I would recommend using regular expressions instead, see this example:

sample_input <- c("123", "not a number")
stringr::str_detect(sample_input, "[^\\d]")
#> [1] FALSE  TRUE
1 Like

You might want to use a numericInput and change its value to character if necessary. Alternatives are using grepl to search for non numeric characters, if your input will be an integer, or using is.numeric() in combination with !is.na().

x <- "23"
!grepl("\\D", x)
#> [1] TRUE

x <- "A2"
!grepl("\\D", x)
#> [1] FALSE

y <- as.numeric("2")
is.numeric(y) & !is.na(y)
#> [1] TRUE

y <- as.numeric("A2")
#> Warning: NAs introduced by coercion
is.numeric(y) & !is.na(y)
#> [1] FALSE

Created on 2019-07-15 by the reprex package (v0.2.1)

1 Like

I suggest converting everything to numeric and checking for NA:

tienda <- as.numeric(input$Tienda)
depto <- as.numeric(input$depto)
articulo <- as.numeric(input$Articulo)

if (is.na(tienda) | is.na(depto) | is.na(articulo)){
  shinyalert(
    "fill every field",
    "Fill TIENDA, DEPTO Y ARTICULO with numeric data",
    type = "error"
  )
} else{
  ...
  })

This will catch blank fields and values that can't be converted to numeric.

1 Like

Thanks a everyone , really appreciate it :slight_smile:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.