Skip to content

Instantly share code, notes, and snippets.

@debruine
Created May 16, 2019 13:04
Show Gist options
  • Save debruine/e096f8142d3b383dc55f195bba5c7b0a to your computer and use it in GitHub Desktop.
Save debruine/e096f8142d3b383dc55f195bba5c7b0a to your computer and use it in GitHub Desktop.
R function to validate the input from readline
#' Check readline input
#'
#' @param prompt the prompt for readline
#' @param type what type of check to perform, one of c("numeric", "character", "length", "minlength", "maxlength", "exact", "grep")
#' @param compare the comparator for exact and (min|max)length types
#' @param ... other arguments to pass to grep
#'
#' @return the validated result of readline
#' @export
#'
#' @examples
#' readline_check("Type a number: ", "numeric")
#' readline_check("Type two characters: ", "length", 2)
#' readline_check("Type at least 3 characters: ", "minlength", 3)
#' readline_check("Type no more than 4 characters: ", "maxlength", 4)
#' readline_check("Type a letter and a number: ", "grep", pattern = "^[a-zA-Z]\\d$")
#'
readline_check <- function(prompt, type = c("numeric", "length", "minlength", "maxlength", "exact", "grep"), compare = NULL, ...) {
input <- readline(prompt)
if (type == "numeric") {
check <- suppressWarnings(!is.na(as.numeric(input)))
} else if (type == "exact") {
check <- input == compare
} else if (type == "length") {
check <- nchar(input) == compare
} else if (type == "minlength") {
check <- nchar(input) >= compare
} else if (type == "maxlength") {
check <- nchar(input) <= compare
} else if (type == "grep") {
check <- grep(x = input, ...) %>% length() > 0
} else {
check <- FALSE # default false if type is wrong?
}
if (!check) {
readline_check(prompt, type[1], compare, ...)
} else {
input
}
}
n <- readline_check("Type a number: ", "numeric")
yes <- readline_check("Type 'yes': ", "exact", "yes")
c2 <- readline_check("Type two characters: ", "length", 2)
c3 <- readline_check("Type at least 3 characters: ", "minlength", 3)
c4 <- readline_check("Type no more than 4 characters: ", "maxlength", 4)
ln <- readline_check("Type a letter and a number: ", "grep", pattern = "^[a-zA-Z]\\d$")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment