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: TImplementations§
Source§impl<T: MessageRenderer> Validator<T>
impl<T: MessageRenderer> Validator<T>
Sourcepub fn with_message(message_renderer: T) -> Validator<T>
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);Sourcepub fn check<U: Checkable + 'static>(&mut self, checker: U) -> &mut Validator<T>
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)));Sourcepub fn validate(&mut self, params: &HashMap<String, Vec<String>>)
pub fn validate(&mut self, params: &HashMap<String, Vec<String>>)
Do the validating logic.
Don’t forget to add checkers first.
Sourcepub fn get_required(&self, name: &str) -> FieldValue
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(¶ms);
assert!(validator.is_valid());
assert_eq!(validator.get_required("name").as_str().unwrap(), "bob".to_string());Sourcepub fn get_optional(&self, name: &str) -> Option<FieldValue>
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(¶ms);
assert!(validator.is_valid());
assert!(validator.get_optional("name").is_none());Sourcepub fn get_required_multiple(&self, name: &str) -> Vec<FieldValue>
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(¶ms);
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()]);Sourcepub fn get_optional_multiple(&self, name: &str) -> Option<Vec<FieldValue>>
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(¶ms);
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()]);Sourcepub fn is_valid(&self) -> bool
pub fn is_valid(&self) -> bool
Tell you whether the validator is valid or not, you must first call
validate method.
Sourcepub fn get_error(&self, name: &str) -> String
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(¶ms);
assert!(!validator.is_valid());
assert_eq!(validator.get_error("name"), "姓名长度不能小于2");Sourcepub fn get_errors(&self) -> Vec<String>
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(¶ms);
assert!(!validator.is_valid());
assert_eq!(validator.get_errors(), vec!["姓名长度不能小于2"]);Sourcepub fn get_some_error(&self) -> String
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(¶ms);
assert!(!validator.is_valid());
assert_eq!(validator.get_some_error(), "姓名长度不能小于2");