Skip to main content

Module validate

Module validate 

Source
Expand description

Composable input validators — ports @clack/core’s runValidation with a library-of-rules on top, and ports utils/string.ts-style helpers.

A validator returns Ok(()) if the value is acceptable, or Err(msg) with the error string to show below the input. Validators compose with & (AND) and | (OR) and can be tagged with custom messages via Validator::msg.

§Example — composing rules in user code

use cli_ui::prompt::{secret, text, min_chars, has_upper, has_lower,
    has_digit, has_special, word_count};

let password = secret("New password")
    .rule(
        min_chars(12)
            .and(has_upper())
            .and(has_lower())
            .and(has_digit())
            .and(has_special())
            .msg("≥12 chars with upper/lower/digit/special required"),
    )
    .run()?;

let seed = text("Recovery phrase")
    .rule(word_count(12))
    .run()?;

§Integrating an external validation crate

Implement the Validate trait for any wrapper around your library of choice (validator, garde, etc.):

use cli_ui::prompt::validate::Validator;

fn from_external(rule: impl Fn(&str) -> Result<(), String> + Send + Sync + 'static) -> Validator {
    Validator::new(rule)
}

Structs§

Validator
Validator handle returned by the helpers in this module. Composes with Validator::and / Validator::or / Validator::msg.

Traits§

Validate
Anything that can decide whether an input string is acceptable.

Functions§

alpha_only
Letters only (Unicode alphabetic).
alphanumeric
Letters and digits only.
email
Looks like an email (very permissive: something@something.something).
ends_with
Ends with suffix.
exact_chars
Exact length in characters.
float_between
Parsable as float in [min, max].
forbid_chars
Reject if any of the given characters appear.
has_digit
At least one ASCII digit.
has_lower
At least one ASCII lowercase character.
has_special
At least one ASCII punctuation/special character.
has_upper
At least one ASCII uppercase character.
int_between
Parsable as integer in [min, max].
max_chars
At most n characters.
min_chars
At least n characters (counted by Unicode chars).
one_of
One of the listed values, case-sensitive.
only_chars
Restrict to a given set of characters.
required
Reject empty input.
starts_with
Starts with prefix.
word_count
Exactly n whitespace-separated words.
words_between
At least one of min..=max words.