Struct Validator

Source
pub struct Validator<T: MessageRenderer = ()> {
    pub checkers: Vec<Box<dyn Checkable>>,
    pub valid_data: HashMap<String, Option<Vec<FieldValue>>>,
    pub invalid_messages: HashMap<String, String>,
    pub message_renderer: T,
}
Expand description

The Validator type.

Each time we want to validate form values, we make a validator.

Firstly, we add checkers to it calling its check method.

Then, we call its validator method to do the validating thing.

Finally, we get valid keys and values from its valid_data member and get invalid keys and messages from its invalid_messages member.

The message_renderer member is used to custom invalid messages.

Fields§

§checkers: Vec<Box<dyn Checkable>>§valid_data: HashMap<String, Option<Vec<FieldValue>>>§invalid_messages: HashMap<String, String>§message_renderer: T

Implementations§

Source§

impl Validator<()>

Source

pub fn new() -> Validator<()>

Constructs a new Validator with the default message renderer.

Source§

impl<T: MessageRenderer> Validator<T>

Source

pub fn with_message(message_renderer: T) -> Validator<T>

Constructs a new Validator with a custom message renderer.

Often, when there are invalid values, we want to show the users why. And you might want to custom the format for kinds of messages, especially, in your native language. You do it by giving a MessageRenderer.

The default message renderer uses Simple Chinese.

§Examples
struct EnglishMessageRenderer;
impl MessageRenderer for EnglishMessageRenderer {
    fn render_message(&self, m: SomeMessage) -> String {
        match m.kind {
            MessageKind::Max => format!("{title} can't be more than {rule}", title=m.title, rule=m.rule_values[0]),
            MessageKind::Min => format!("{title} can't be less than {rule}", title=m.title, rule=m.rule_values[0]),
            MessageKind::MaxLen => format!("{title} can't be longer than {rule}", title=m.title, rule=m.rule_values[0]),
            MessageKind::MinLen => format!("{title} can't be shorter than {rule}", title=m.title, rule=m.rule_values[0]),
            MessageKind::Blank => format!("{title} is missing", title=m.title),
            MessageKind::Format => format!("{title} is in wrong format", title=m.title),
        }
    }
}
let mut validator = Validator::with_message(EnglishMessageRenderer);
Source

pub fn check<U: Checkable + 'static>(&mut self, checker: U) -> &mut Validator<T>

Add a checker to this validator.

We can chain this call to add multiple checkers.

§Examples
let mut validator = Validator::new();
// Add Checkers to Validator.
validator
    .check(Checker::new("name", "姓名", Str)
           .meet(Rule::Max(5))
           .meet(Rule::Min(2)))
    .check(Checker::new("age", "年龄", I64)
           .meet(Rule::Max(100))
           .meet(Rule::Min(18)));
Source

pub fn validate(&mut self, params: &HashMap<String, Vec<String>>)

Do the validating logic.

Don’t forget to add checkers first.

Source

pub fn get_required(&self, name: &str) -> FieldValue

Get a required valid value after validating.

§Panics

Call this method when you’re sure the value exists and is valid, or it panics!

You may want to call is_valid method first, when that is true, you have confidence that this call will not panic!

§Examples
let mut params = std::collections::HashMap::new();
params.insert("name".to_string(), vec!["bob".to_string()]);

let mut validator = Validator::new();
validator
    .check(Checker::new("name", "姓名", Str)
           .meet(Rule::Max(5))
           .meet(Rule::Min(2)));
validator.validate(&params);
assert!(validator.is_valid());
assert_eq!(validator.get_required("name").as_str().unwrap(), "bob".to_string());
Source

pub fn get_optional(&self, name: &str) -> Option<FieldValue>

Get a optional valid value after validating.

This method is for getting optional values, the value which is allowed to be missing.

Refer to CheckerOption::Optional

§Panics

You may want to call is_valid method first, when that is true, you have confidence that this call will not panic!

§Examples
let mut params = std::collections::HashMap::new();

let mut validator = Validator::new();
validator
    .check(Checker::new("name", "姓名", Str)
           .set(CheckerOption::Optional(true))
           .meet(Rule::Max(5))
           .meet(Rule::Min(2)));
validator.validate(&params);
assert!(validator.is_valid());
assert!(validator.get_optional("name").is_none());
Source

pub fn get_required_multiple(&self, name: &str) -> Vec<FieldValue>

Get multiple valid values after validating.

Sometimes we need a vector of values which have the same field name.

This method is for getting required multiple values

Refer to CheckerOption::Multiple

§Panics

You may want to call is_valid method first, when that is true, you have confidence that this call will not panic!

§Examples
let mut params = std::collections::HashMap::new();
params.insert("name".to_string(), vec!["bob".to_string(), "mary".to_string()]);

let mut validator = Validator::new();
validator
    .check(Checker::new("name", "姓名", Str)
           .set(CheckerOption::Multiple(true))
           .meet(Rule::Max(5))
           .meet(Rule::Min(2)));
validator.validate(&params);
assert!(validator.is_valid());
assert_eq!(validator.get_required_multiple("name").iter().map(|item| item.as_str().unwrap()).collect::<Vec<_>>(), vec!["bob".to_string(), "mary".to_string()]);
Source

pub fn get_optional_multiple(&self, name: &str) -> Option<Vec<FieldValue>>

Get optional multiple valid values after validating.

Sometimes we need a vector of values which have the same field name.

This method is for getting optional multiple values

Refer to CheckerOption

§Panics

You may want to call is_valid method first, when that is true, you have confidence that this call will not panic!

§Examples
let mut params = std::collections::HashMap::new();
params.insert("name".to_string(), vec!["bob".to_string(), "mary".to_string()]);

let mut validator = Validator::new();
validator
    .check(Checker::new("name", "姓名", Str)
           .set(CheckerOption::Multiple(true))
           .set(CheckerOption::Optional(true))
           .meet(Rule::Max(5))
           .meet(Rule::Min(2)));
validator.validate(&params);
assert!(validator.is_valid());
assert_eq!(validator.get_optional_multiple("name").unwrap().iter().map(|item| item.as_str().unwrap()).collect::<Vec<_>>(), vec!["bob".to_string(), "mary".to_string()]);
Source

pub fn is_valid(&self) -> bool

Tell you whether the validator is valid or not, you must first call validate method.

Source

pub fn get_error(&self, name: &str) -> String

Get an error message by field name.

§Panics

Make sure you know this field is invalid before you get its message, or it panics.

§Examples
let mut params = std::collections::HashMap::new();
params.insert("name".to_string(), vec!["b".to_string()]);

let mut validator = Validator::new();
validator
    .check(Checker::new("name", "姓名", Str)
           .meet(Rule::Max(5))
           .meet(Rule::Min(2)));
validator.validate(&params);
assert!(!validator.is_valid());
assert_eq!(validator.get_error("name"), "姓名长度不能小于2");
Source

pub fn get_errors(&self) -> Vec<String>

Get all error messages as a vector.

§Examples
let mut params = std::collections::HashMap::new();
params.insert("name".to_string(), vec!["b".to_string()]);

let mut validator = Validator::new();
validator
    .check(Checker::new("name", "姓名", Str)
           .meet(Rule::Max(5))
           .meet(Rule::Min(2)));
validator.validate(&params);
assert!(!validator.is_valid());
assert_eq!(validator.get_errors(), vec!["姓名长度不能小于2"]);
Source

pub fn get_some_error(&self) -> String

Get an arbitrary error message.

§Panics

Make sure you know the validator is invalid before you get some message, or it panics.

§Examples
let mut params = std::collections::HashMap::new();
params.insert("name".to_string(), vec!["b".to_string()]);

let mut validator = Validator::new();
validator
    .check(Checker::new("name", "姓名", Str)
           .meet(Rule::Max(5))
           .meet(Rule::Min(2)));
validator.validate(&params);
assert!(!validator.is_valid());
assert_eq!(validator.get_some_error(), "姓名长度不能小于2");
Source

pub fn reset(&mut self)

Clear the valid_data and invalid_messages, as if you have not called validate.

Auto Trait Implementations§

§

impl<T> Freeze for Validator<T>
where T: Freeze,

§

impl<T = ()> !RefUnwindSafe for Validator<T>

§

impl<T = ()> !Send for Validator<T>

§

impl<T = ()> !Sync for Validator<T>

§

impl<T> Unpin for Validator<T>
where T: Unpin,

§

impl<T = ()> !UnwindSafe for Validator<T>

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> 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, 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.