[][src]Crate validator

Example:

This example is not tested
use serde::Deserialize;

// A trait that the Validate derive will impl
use validator::{Validate, ValidationError};

#[derive(Debug, Validate, Deserialize)]
struct SignupData {
    #[validate(email)]
    mail: String,
    #[validate(phone)]
    phone: String,
    #[validate(url)]
    site: String,
    #[validate(length(min = 1), custom = "validate_unique_username")]
    #[serde(rename = "firstName")]
    first_name: String,
    #[validate(range(min = 18, max = 20))]
    age: u32,
}

fn validate_unique_username(username: &str) -> Result<(), ValidationError> {
    if username == "xXxShad0wxXx" {
        // the value of the username will automatically be added later
        return Err(ValidationError::new("terrible_username"));
    }

    Ok(())
}

match signup_data.validate() {
  Ok(_) => (),
  Err(e) => return e;
};

Available Validations:

ValidationNotes
email
url
length
range
must_match
contains
customThis validator can also be used on then entire struct
regex
credit_card(Requires the feature card to be enabled)
phone(Requires the feature phone to be enabled)
non_control_character(Required the feature unic to be enabled)
nested(Uses the validation of the field type it self)
required

Checkout the project README of an in-depth usage description with examples.

Installation:

Add the validator to the dependencies in the Cargo.toml file.

[dependencies]
validator = { version = "0.12", features = ["derive"] }

Structs

ValidationError
ValidationErrors

Enums

ValidationErrorsKind
Validator

Contains all the validators that can be used

Traits

Contains

Trait to implement if one wants to make the contains validator work for more types

HasLen

Trait to implement if one wants to make the length validator work for more types

Validate

The trait that validator_derive implements

Functions

validate_contains

Validates whether the value contains the needle The value needs to implement the Contains trait, which is implement on String, str and Hashmap by default.

validate_email

Validates whether the given string is an email based on the HTML5 spec. RFC 5322 is not practical in most circumstances and allows email addresses that are unfamiliar to most users.

validate_ip

Validates whether the given string is an IP

validate_ip_v4

Validates whether the given string is an IP V4

validate_ip_v6

Validates whether the given string is an IP V6

validate_length

Validates the length of the value given. If the validator has equal set, it will ignore any min and max value.

validate_must_match

Validates that the 2 given fields match. Both fields are optionals

validate_range

Validates that the given value is inside the defined range. The max and min parameters are optional and will only be validated if they are not None

validate_required

Validates whether the given Option is Some

validate_url

Validates whether the string given is a url