Module webforms::validate

source ·
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):

attributefield typevalue typedescriptionNotes
min_lengthStringIntegerChecks if input meets a required minimum length
max_lengthStringIntegerChecks if input is under or equal to a maximum length
regexStringStringChecks if input is a match against the supplied regex1
emailStringNoneChecks if input matches an email address (via regex)1
phoneStringNoneChecks if input matches a phone number (via regex)2
min_valueInteger/FloatInteger/FloatChecks if input is greater than or equal to specified value
max_valueInteger/FloatInteger/FloatChecks if input is less than or euqal to specified value

Notes:

  • 1 - Requires crate to depend on regex and lazy_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