Expand description
Validates a stuct’s fields according the attributes applied to each field.
Provides a derive macro to auto-implement the ValidateForm trait that
supports the validate(&self)
method. Current attributes (and support types):
attribute | field type | value type | description | Notes |
---|---|---|---|---|
min_length | String | Integer | Checks if input meets a required minimum length | |
max_length | String | Integer | Checks if input is under or equal to a maximum length | |
regex | String | String | Checks if input is a match against the supplied regex | 1 |
String | None | Checks if input matches an email address (via regex) | 1 | |
phone | String | None | Checks if input matches a phone number (via regex) | 2 |
min_value | Integer/Float | Integer/Float | Checks if input is greater than or equal to specified value | |
max_value | Integer/Float | Integer/Float | Checks if input is less than or euqal to specified value |
Notes:
- 1 - Requires crate to depend on
regex
andlazy_static
crates and import them. See below for example. - 2 - Currently only matches on US phone numbers
Example
use lazy_static::lazy_static;
use regex::Regex;
use webforms::validate::{ValidateForm, ValidateError};
#[derive(ValidateForm)]
struct LoginForm {
#[validate(email)]
pub email: String,
#[validate(min_length = 8)]
#[validate(max_length = 20)]
pub password: String,
}
fn main() {
let form = LoginForm {
email: "test@someemail.com".to_owned(),
password: "itsasecret".to_owned(),
};
if let Err(e) = form.validate() {
println!("{:?}", e);
}
}
Enums
Errors that can appear if validation fails
Traits
Validates a form according to attributes set via #[validate] attribute
on a given struct. The attributes are set on the individual fields in
a struct.
Derive Macros
Import and re-export the macro
Derives the ValidateForm trait from for a given struct