#[derive(Validate)]
{
// Attributes available to this derive:
#[validate]
}
Expand description
Enables the use of #[validate] attributes on struct/enum fields and
implements the Validate trait based on the provided attributes.
Visit the repository to see the list of available validations and modifiers, as well as more examples.
§Example
ⓘ
use validify::{ValidationError, ValidationErrors, Validate};
#[derive(Debug, Validate, Deserialize)]
#[validate(validate_signup)]
struct SignupData {
#[validate(email)]
mail: String,
#[validate(url)]
site: String,
#[validate(
length(min = 1),
custom(validate_unique_username)
)]
first_name: String,
#[validate(range(min = 18., max = 20.))]
age: u32,
}
fn validate_unique_username(username: &str) -> Result<(), ValidationError> {
if username == "xXxShad0wxXx" {
return Err(ValidationError::new_field(
"terrible_username",
));
}
Ok(())
}
fn validate_signup(data: &SignupData) -> Result<(), ValidationErrors> {
let mut errs = ValidationErrors::new();
if data.mail.ends_with("gmail.com") && data.age == 18 {
errs.add(ValidationError::new_schema("stupid_rule"));
}
if errs.is_empty() {
return Ok(());
}
Err(errs)
}
let signup = SignupData {
mail: "bob@bob.com".to_string(),
site: "http://hello.com".to_string(),
first_name: "Bob".to_string(),
age: 18,
};
assert!(signup.validate().is_ok());