Skip to main content

InputValidator

Trait InputValidator 

Source
pub trait InputValidator {
    // Required method
    fn check(&self, input: &str) -> Result<(), String>;
}
Expand description

Input validator trait

§Examples

Simple validation with a function pointer

use demand::Input;

fn not_empty(s: &str) -> Result<(), &'static str> {
     if s.is_empty() {
         return Err("Name cannot be empty");
     }
     Ok(())
}

let input = Input::new("What's your name?")
    .validation(not_empty);
// input.run() would block waiting for user input

Dynamic validation

use demand::{Input, InputValidator};

struct NameValidation {
    max_length: usize,
}

impl InputValidator for NameValidation {
    fn check(&self, input: &str) -> Result<(), String> {
        if input.len() > self.max_length {
            return Err(format!(
                "Name must be at most {} characters, got {}",
                self.max_length,
                input.len()
            ));
        }
        Ok(())
    }
}

let input = Input::new("What's your name?")
    .validator(NameValidation { max_length: 50 });
// input.run() would block waiting for user input

Required Methods§

Source

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

Implementations on Foreign Types§

Source§

impl InputValidator for fn(&str) -> Result<(), &str>

Source§

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

Implementors§

Source§

impl<F, Err> InputValidator for F
where F: Fn(&str) -> Result<(), Err>, Err: ToString,