Here is a solution using HTML rather than Shiny. The solution is to add a pattern
attribute to the HTML input tag. It will not remove the undesired characters, but the field will turn, say, pink to let the user know that an invalid character has been typed.
1-- Let the background becomes pink when invalid is raised. For that, we need to add a style in the CSS. In Shiny, this is achieved by adding in the ui a style
tag in the head
tag that will be attached to input[type='text']:invalid
with
tags$head(
tags$style(HTML("input[type='text']:invalid {background-color: pink;}"))
)
2-- create the ui with the above as well as a text input field, e.g.:
ui <- fluidPage(
tags$head(
tags$style(HTML("input[type='text']:invalid {background-color: pink;}"))
),
textInput("mySolution", label = "Only letters are valid here", value = ""),
)
3-- modify this ui to add a pattern
to the input tag:
ui <- searchreplaceit(ui, "input", list(id="mySolution"),
"input", list(pattern="[A-Za-z]*"), replace=FALSE)
This is it! the server function does not need anything, as validation is all performed whithin the page. Launch the page with
server <- function(input, output, session) { }
shinyApp(ui = ui, server = server)
The function to add attributes to a tag is given here
searchreplaceit <- function(branch, whattag, whatattribs, totag, toattribs, replace=TRUE) {
if ("name" %in% names(branch)) {
if ((branch$name == whattag)&&(identical( branch$attribs[names(whatattribs)], whatattribs))) {
branch$name <- totag
branch$attribs <- if (replace) {toattribs} else { modifyList(branch$attribs, toattribs)}
}
}
if ("shiny.tag" %in% class(branch)) {
if (length(branch$children)>0) for (i in 1: length(branch$children)) {
if (!(is.null(branch$children[[i]]))) {
branch$children[[i]] = searchreplaceit(branch$children[[i]], whattag, whatattribs, totag, toattribs, replace)
} }
} else if ("list" %in% class(branch)) {
if (length(branch)>0) for (i in 1:length(branch) ) {
if (!(is.null(branch[[i]]))) {
branch[[i]] <- searchreplaceit(branch[[i]], whattag, whatattribs, totag, toattribs, replace)
} }
}
return(branch)
}
A related version was given in Edit a shiny.tag element
When you do not type a letter:
numeric_only=T
argument innumericInput
. I want it to be impossible for the user to enter a character value in a numeric field. – Mcbrayer