Skip to main content

Validator

Struct Validator 

Source
pub struct Validator(/* private fields */);
Expand description

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

Implementations§

Source§

impl Validator

Source

pub fn new<V: Validate>(v: V) -> Self

Wrap any Validate implementation — including a plain closure |s: &str| -> Result<(), String> — into a Validator.

Examples found in repository?
examples/prompt_validate.rs (lines 17-25)
9fn main() {
10    let _ = colors(); // silence unused-import warning if you remove theming below
11
12    intro("Validation playground");
13
14    let abort = "Aborted — nothing was saved.";
15
16    // 12-word seed phrase, composed from primitives.
17    let lowercase_words = Validator::new(|v: &str| {
18        if v.split_whitespace()
19            .all(|w| w.chars().all(|c| c.is_ascii_lowercase()))
20        {
21            Ok(())
22        } else {
23            Err("Words must be lowercase ASCII".into())
24        }
25    });
26    let _seed = text("Recovery phrase")
27        .rule(word_count(12).and(lowercase_words))
28        .run()
29        .or_cancel(abort);
30
31    let _pw = secret("Set a password")
32        .rule(
33            min_chars(12)
34                .and(has_upper())
35                .and(has_lower())
36                .and(has_digit())
37                .and(has_special())
38                .msg("≥12 chars with upper, lower, digit, and a special char"),
39        )
40        .run()
41        .or_cancel(abort);
42
43    let _mail = text("Email")
44        .placeholder("you@example.com")
45        .rule(email())
46        .run()
47        .or_cancel(abort);
48
49    let _port = text("Listen port")
50        .default("8080")
51        .rule(int_between(1024, 65535))
52        .run()
53        .or_cancel(abort);
54
55    let _user = text("Username")
56        .rule(
57            min_chars(3)
58                .and(max_chars(20))
59                .and(alphanumeric())
60                .msg("3–20 alphanumeric characters"),
61        )
62        .run()
63        .or_cancel(abort);
64
65    let _name = text("Display name")
66        .validate(|s: &str| {
67            if s.contains(char::is_whitespace) {
68                Err("No spaces allowed".into())
69            } else {
70                Ok(())
71            }
72        })
73        .run()
74        .or_cancel(abort);
75
76    outro("All validators passed!");
77}
Source

pub fn check(&self, v: &str) -> Result<(), String>

Run the validator. Mirrors Validate::check.

Source

pub fn and(self, other: Validator) -> Validator

Both must pass. Returns the first error encountered.

Examples found in repository?
examples/prompt_validate.rs (line 27)
9fn main() {
10    let _ = colors(); // silence unused-import warning if you remove theming below
11
12    intro("Validation playground");
13
14    let abort = "Aborted — nothing was saved.";
15
16    // 12-word seed phrase, composed from primitives.
17    let lowercase_words = Validator::new(|v: &str| {
18        if v.split_whitespace()
19            .all(|w| w.chars().all(|c| c.is_ascii_lowercase()))
20        {
21            Ok(())
22        } else {
23            Err("Words must be lowercase ASCII".into())
24        }
25    });
26    let _seed = text("Recovery phrase")
27        .rule(word_count(12).and(lowercase_words))
28        .run()
29        .or_cancel(abort);
30
31    let _pw = secret("Set a password")
32        .rule(
33            min_chars(12)
34                .and(has_upper())
35                .and(has_lower())
36                .and(has_digit())
37                .and(has_special())
38                .msg("≥12 chars with upper, lower, digit, and a special char"),
39        )
40        .run()
41        .or_cancel(abort);
42
43    let _mail = text("Email")
44        .placeholder("you@example.com")
45        .rule(email())
46        .run()
47        .or_cancel(abort);
48
49    let _port = text("Listen port")
50        .default("8080")
51        .rule(int_between(1024, 65535))
52        .run()
53        .or_cancel(abort);
54
55    let _user = text("Username")
56        .rule(
57            min_chars(3)
58                .and(max_chars(20))
59                .and(alphanumeric())
60                .msg("3–20 alphanumeric characters"),
61        )
62        .run()
63        .or_cancel(abort);
64
65    let _name = text("Display name")
66        .validate(|s: &str| {
67            if s.contains(char::is_whitespace) {
68                Err("No spaces allowed".into())
69            } else {
70                Ok(())
71            }
72        })
73        .run()
74        .or_cancel(abort);
75
76    outro("All validators passed!");
77}
Source

pub fn or(self, other: Validator) -> Validator

At least one must pass. Returns the second error if both fail (usually more user-friendly than “you failed multiple things”).

Source

pub fn msg(self, message: impl Into<String>) -> Validator

Replace the error message produced by this validator.

Examples found in repository?
examples/prompt_validate.rs (line 38)
9fn main() {
10    let _ = colors(); // silence unused-import warning if you remove theming below
11
12    intro("Validation playground");
13
14    let abort = "Aborted — nothing was saved.";
15
16    // 12-word seed phrase, composed from primitives.
17    let lowercase_words = Validator::new(|v: &str| {
18        if v.split_whitespace()
19            .all(|w| w.chars().all(|c| c.is_ascii_lowercase()))
20        {
21            Ok(())
22        } else {
23            Err("Words must be lowercase ASCII".into())
24        }
25    });
26    let _seed = text("Recovery phrase")
27        .rule(word_count(12).and(lowercase_words))
28        .run()
29        .or_cancel(abort);
30
31    let _pw = secret("Set a password")
32        .rule(
33            min_chars(12)
34                .and(has_upper())
35                .and(has_lower())
36                .and(has_digit())
37                .and(has_special())
38                .msg("≥12 chars with upper, lower, digit, and a special char"),
39        )
40        .run()
41        .or_cancel(abort);
42
43    let _mail = text("Email")
44        .placeholder("you@example.com")
45        .rule(email())
46        .run()
47        .or_cancel(abort);
48
49    let _port = text("Listen port")
50        .default("8080")
51        .rule(int_between(1024, 65535))
52        .run()
53        .or_cancel(abort);
54
55    let _user = text("Username")
56        .rule(
57            min_chars(3)
58                .and(max_chars(20))
59                .and(alphanumeric())
60                .msg("3–20 alphanumeric characters"),
61        )
62        .run()
63        .or_cancel(abort);
64
65    let _name = text("Display name")
66        .validate(|s: &str| {
67            if s.contains(char::is_whitespace) {
68                Err("No spaces allowed".into())
69            } else {
70                Ok(())
71            }
72        })
73        .run()
74        .or_cancel(abort);
75
76    outro("All validators passed!");
77}

Trait Implementations§

Source§

impl Clone for Validator

Source§

fn clone(&self) -> Validator

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<F> From<F> for Validator
where F: Fn(&str) -> Result<(), String> + Send + Sync + 'static,

Source§

fn from(f: F) -> Self

Converts to this type from the input type.
Source§

impl Validate for Validator

Source§

fn check(&self, v: &str) -> Result<(), String>

Return Ok(()) to accept the value, Err(msg) to reject and show msg as the user-facing error.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.