Struct form_checker::Validator [] [src]

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

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

Methods

impl Validator<()>
[src]

Constructs a new Validator with the default message renderer.

impl<T: MessageRenderer> Validator<T>
[src]

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);

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)));

Do the validating logic.

Don't forget to add checkers first.

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());

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());

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()]);

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()]);

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

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");

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"]);

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");

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