validate field attributes

Learn the validator field attributes email, length, range, and required, what each one checks, and how to give each rule a custom message

A field attribute is the #[validate(...)] note above a struct field that states one rule for that field. The word inside the parentheses names the rule, and the arguments after it set the rule's limits. This page covers the four attributes you reach for first: email, length, range, and required, plus the message argument that replaces the default error text with words of your own.

Where This Fits

The validate derive feature page showed how the derive macro reads attributes and generates a validate() method. That page used one attribute, email, without explaining what it checks or what else exists. This page is the vocabulary: the four common attributes, the exact arguments each one takes, and the message each failure carries.

Think of the attributes as four different measuring tools on a workbench. One checks shape, one checks length, one checks size, and one checks presence. Each tool has its own dials, and picking the wrong tool for a field is the most common mistake in this group.

The Smallest Working Version

One struct with all four attributes shows the whole vocabulary in a single place. Each field carries one rule, and the main runs a good value and a bad value through validate().

src/main.rs
use validator::Validate;

#[derive(Debug, Validate)]
struct Signup {
    #[validate(email)]
    email: String,
    #[validate(length(min = 3, max = 30))]
    name: String,
    #[validate(range(min = 18, max = 120))]
    age: u32,
    #[validate(required)]
    nickname: Option<String>,
}

fn main() {
    let good = Signup {
        email: "ada@example.com".to_string(),
        name: "Ada".to_string(),
        age: 30,
        nickname: Some("ada".to_string()),
    };
    println!("good: {:?}", good.validate());

    let bad = Signup {
        email: "not-an-email".to_string(),
        name: "Al".to_string(),
        age: 12,
        nickname: None,
    };
    println!("bad: {:?}", bad.validate());
}

The good value prints Ok(()). The bad value prints one Err with four entries, and each entry carries a code naming the rule that failed: email, length, range, required. Those four codes are the names you will see in error responses, so they are worth learning now.

good: Ok(())
bad: Err(ValidationErrors({"email": Field([ValidationError { code: "email", message: None, params: {"value": String("not-an-email")} }]), "age": Field([ValidationError { code: "range", message: None, params: {"value": Number(12), "min": Number(18), "max": Number(120)} }]), "nickname": Field([ValidationError { code: "required", message: None, params: {"value": Null} }]), "name": Field([ValidationError { code: "length", message: None, params: {"max": Number(30), "value": String("Al"), "min": Number(3)} }])}))

Every entry also carries params, a map with the details of the failed check. The range entry shows the value 12 beside min 18 and max 120. The length entry shows the value "Al" beside min 3 and max 30. The message field is None in every entry, because no custom message was written yet. The message argument is covered later on this page.

Working Setup:

If the bad value prints four entries with the codes email, length, range, and required, all four attributes are working. A missing entry means the attribute on that field is misspelled or missing.

email - Checking the Shape of an Address

The email attribute checks whether a string looks like an email address. It takes no arguments.

#[validate(email)]
email: String,

The check follows the email pattern from the HTML5 specification, the same pattern browsers use for an email input box. It is a pattern match on the shape of the text, not a check that the address really exists. No email is sent, no domain is looked up, and no mailbox is contacted. The rule only answers whether the string is shaped like an address.

That distinction matters, because the pattern accepts addresses a person might not expect. The string "a@b" passes the check, because it has local text, an @ sign, and domain text, which is all the pattern asks for. The string "not-an-email" fails, because it has no @ sign at all. The string "ada@" fails, because there is nothing after the @ sign. Both results below were run against validator 0.21.0 while checking the examples for this page.

src/main.rs
use validator::Validate;

#[derive(Debug, Validate)]
struct Contact {
    #[validate(email)]
    email: String,
}

fn main() {
    for address in ["ada@example.com", "a@b", "not-an-email", "ada@", "@example.com"] {
        let contact = Contact {
            email: address.to_string(),
        };
        println!("{:?} -> {:?}", address, contact.validate());
    }
}

The output shows which shapes pass and which fail.

"ada@example.com" -> Ok(())
"a@b" -> Ok(())
"not-an-email" -> Err(ValidationErrors({"email": Field([ValidationError { code: "email", message: None, params: {"value": String("not-an-email")} }])}))
"ada@" -> Err(ValidationErrors({"email": Field([ValidationError { code: "email", message: None, params: {"value": String("ada@")} }])}))
"@example.com" -> Err(ValidationErrors({"email": Field([ValidationError { code: "email", message: None, params: {"value": String("@example.com")} }])}))

A beginner reading this output learns the rule's real boundary: it rejects text that is plainly not an address, and it accepts anything shaped like one, even a short or unlikely address. If your application needs to know that an address can receive mail, that check happens later, by sending a confirmation message. The attribute only guards the shape.

The email attribute works on String and str fields. It also works on an Option<String> field, where it is only checked when the value is Some. A None value skips the rule and passes, which is the general behaviour of every attribute on an Option field.

Email Checks Shape, Not Existence:

The email rule never sends mail and never looks up a domain. An address can pass this check and still belong to nobody. Treat the attribute as a first filter against typos and wrong fields, not as proof that the address is real.

length - Checking How Long a Value Is

The length attribute checks how long a string or a list is. It takes three possible arguments, and at least one of them must be present: min, max, or equal.

#[validate(length(min = 3, max = 30))]
name: String,

The min argument is the smallest length allowed, and max is the largest length allowed. Both limits are inclusive, which means the boundary values themselves pass. A name of exactly 3 characters passes min = 3, and a name of exactly 30 characters passes max = 30. A name of 2 characters fails, and a name of 31 characters fails. Inclusive limits are easy to get wrong by one, so the boundary behaviour is worth stating plainly: the limits themselves are allowed.

Either min or max may be left out, but not both. A rule with only min sets a floor and no ceiling. A rule with only max sets a ceiling and no floor. A rule with neither is a compile error, because it would check nothing.

src/main.rs
use validator::Validate;

#[derive(Debug, Validate)]
struct Post {
    #[validate(length(min = 1))]
    title: String,
    #[validate(length(max = 280))]
    body: String,
    #[validate(length(equal = 6))]
    code: String,
}

fn main() {
    let post = Post {
        title: "".to_string(),
        body: "hello".to_string(),
        code: "ABC123".to_string(),
    };
    println!("{:?}", post.validate());
}

The title fails here, because an empty string has length 0 and min = 1 requires at least 1 character. The body passes, because 5 characters sit under the ceiling of 280. The code passes, because equal = 6 requires exactly 6 characters and "ABC123" has exactly 6. The equal argument is a third option: it requires one exact length, and it cannot be combined with min or max. Writing length(equal = 6, min = 3) is a compile error.

Length is counted in characters, not in bytes. A string is stored as UTF-8, where some characters take more than one byte, but the rule counts the characters a reader sees. Two accented characters such as "éé" count as length 2, even though they take 4 bytes to store. That behaviour was checked by running the crate: "éé" fails length(min = 3) and "ééé" passes it. Counting characters is what a user expects when a form says a name must be at least 3 characters long.

The same attribute works on a Vec, where it counts items instead of characters. A list of tags with length(min = 1, max = 5) must hold between 1 and 5 items. The rule does not look inside the items. It only counts them.

#[derive(Debug, Validate)]
struct Article {
    #[validate(length(min = 1, max = 5))]
    tags: Vec<String>,
}

A length rule on a number does not compile, because a number has a value, not a length. The rule for numbers is range, covered next.

range - Checking Whether a Number Sits Between Two Limits

The range attribute checks whether a number sits between a minimum and a maximum. It takes min and max arguments, and the exclusive variants exclusive_min and exclusive_max.

#[validate(range(min = 18, max = 120))]
age: u32,

Like length, both limits are inclusive by default. An age of exactly 18 passes, and an age of exactly 120 passes. An age of 17 fails, and an age of 121 fails. Either limit may be left out, but not both. A rule with only min sets a floor, and a rule with only max sets a ceiling.

src/main.rs
use validator::Validate;

#[derive(Debug, Validate)]
struct Limits {
    #[validate(range(min = 1))]
    count: i32,
    #[validate(range(max = 100))]
    score: i32,
    #[validate(range(exclusive_min = 0, max = 10))]
    rating: i32,
}

fn main() {
    let good = Limits {
        count: 5,
        score: 100,
        rating: 1,
    };
    println!("good: {:?}", good.validate());

    let bad = Limits {
        count: 0,
        score: 101,
        rating: 0,
    };
    println!("bad: {:?}", bad.validate());
}

The good value passes on all three fields. The bad value fails all three: 0 sits below the floor of 1, 101 sits above the ceiling of 100, and 0 sits on the exclusive floor. The exclusive_min argument means the boundary value itself fails. With exclusive_min = 0, the value 0 fails and the value 1 passes. The exclusive variants exist for rules where the boundary is not a legal value, such as a quantity that must be more than zero rather than zero or more. The same idea applies to exclusive_max: with exclusive_max = 10, the value 10 fails and the value 9 passes.

Range works on integers and on floating point numbers. A price field of type f64 can carry range(min = 0.0, max = 999.99), with the limits written as decimal numbers to match the field type. The limits must be written in the same kind of number as the field, so an integer field takes integer limits and a floating point field takes decimal limits. Mixing them is a compile error.

The range rule checks one field at a time. It cannot compare two fields with each other, so a rule such as "the end date must be after the start date" does not belong here. That kind of cross-field rule needs a custom validator, which is outside this page.

required - Checking That an Optional Field Is Present

The required attribute checks whether an Option field holds a value. It takes no arguments, and it only makes sense on Option fields.

#[validate(required)]
nickname: Option<String>,

An Option in Rust is a value that is either Some with data inside, or None with nothing inside. It is how Rust represents a field that may be missing. Every other attribute on an Option field is skipped when the field is None, because there is no value to check. The required attribute is the exception: it fails exactly when the field is None, and passes when the field is Some, whatever the value inside is.

src/main.rs
use validator::Validate;

#[derive(Debug, Validate)]
struct Profile {
    #[validate(required)]
    nickname: Option<String>,
    #[validate(email)]
    email: Option<String>,
}

fn main() {
    let missing_both = Profile {
        nickname: None,
        email: None,
    };
    println!("missing both: {:?}", missing_both.validate());

    let present = Profile {
        nickname: Some("ada".to_string()),
        email: Some("not-an-email".to_string()),
    };
    println!("present: {:?}", present.validate());
}

The first value fails only on nickname. The email field is None, so its email rule is skipped and it passes. The second value fails only on email. The nickname field is Some, so the required rule passes, and the email rule runs on the text inside and fails. The output shows the split clearly: required guards presence, and every other rule guards the value inside.

missing both: Err(ValidationErrors({"nickname": Field([ValidationError { code: "required", message: None, params: {"value": Null} }])}))
present: Err(ValidationErrors({"email": Field([ValidationError { code: "email", message: None, params: {"value": String("not-an-email")} }])}))

Putting required on a field that is not an Option is a compile error. A plain String field is always present by construction: serde refuses to build the struct when the JSON omits it, so there is nothing for required to check. The attribute exists for the case where the field is allowed to be absent in the JSON but must be present for this particular use.

Required and Optional Are Different Questions:

Whether a field may be missing from the JSON is decided by the field type: Option means it may be missing, plain String means it must be there. Whether a missing value is acceptable is decided by required. The two questions are separate, and the attribute answers only the second one.

Combining Several Rules on One Field

A field can carry more than one rule. Write the rules inside one #[validate(...)] attribute, separated by commas, and the derive macro runs each of them. A password field, for example, can require a minimum length and forbid a blank value at the same time.

src/main.rs
use validator::Validate;

#[derive(Debug, Validate)]
struct Account {
    #[validate(email, length(max = 100))]
    email: String,
    #[validate(length(min = 8, max = 64))]
    password: String,
}

fn main() {
    let account = Account {
        email: "not-an-email".to_string(),
        password: "short".to_string(),
    };
    println!("{:?}", account.validate());
}

Both rules on the email field run, and the password rule runs too, so this value fails on both fields in one call. When a field fails two of its own rules at once, both failures appear in the list for that field. A field's entry in the error map is a list precisely because of this: one field, several rules, several possible failures.

Writing each rule in its own #[validate(...)] attribute on the same field also works, but one attribute with commas is the usual style. It keeps all the rules for a field in one place, so a reader sees the full set of requirements without scanning several lines.

Custom Messages with the message Argument

So far every error entry has shown message: None. That is because no custom message was written, and the crate leaves the message empty when none is given. The message argument fills that gap. It goes inside the rule it belongs to, after the rule's other arguments, and it holds the text a user should see.

#[validate(email(message = "enter a valid email address"))]
email: String,

The placement matters and is easy to get wrong. The message argument belongs inside the parentheses of the rule, not at the end of the #[validate(...)] attribute. Writing #[validate(email, message = "...")] fails to compile, because the attribute itself has no message argument. The compiler reports it plainly.

error: Unknown field: `message`

Each rule carries its own message, so a field with two rules can give each failure different words.

src/main.rs
use validator::Validate;

#[derive(Debug, Validate)]
struct Signup {
    #[validate(email(message = "enter a valid email address"))]
    email: String,
    #[validate(length(min = 3, max = 30, message = "name must be between 3 and 30 characters"))]
    name: String,
    #[validate(range(min = 18, max = 120, message = "age must be between 18 and 120"))]
    age: u32,
    #[validate(required(message = "nickname is required"))]
    nickname: Option<String>,
}

fn main() {
    let bad = Signup {
        email: "nope".to_string(),
        name: "Al".to_string(),
        age: 200,
        nickname: None,
    };
    println!("{:?}", bad.validate());
}

The output now carries a message in every entry.

Err(ValidationErrors({"email": Field([ValidationError { code: "email", message: Some("enter a valid email address"), params: {"value": String("nope")} }]), "age": Field([ValidationError { code: "range", message: Some("age must be between 18 and 120"), params: {"value": Number(200), "max": Number(120), "min": Number(18)} }]), "nickname": Field([ValidationError { code: "required", message: Some("nickname is required"), params: {"value": Null} }]), "name": Field([ValidationError { code: "length", message: Some("name must be between 3 and 30 characters"), params: {"max": Number(30), "value": String("Al"), "min": Number(3)} }])}))

The code field still says which rule failed, and the message field now holds the human-readable text. Both are kept, because they serve different readers. The code is stable text a program can match on, such as "email" or "range". The message is display text a person reads. A handler that builds an error response uses the message for the user and can keep the code for logging or for a client that wants to react to a specific rule.

When no message is written, the message field is None, and code that reads errors must decide what to show instead. The usual fallback is the rule's code, so a missing message still produces some text. That fallback is the shape the handler page uses: message when present, code when absent.

Message Goes Inside the Rule:

Writing #[validate(email, message = "...")] fails to compile with "Unknown field: message". The argument belongs inside the rule: #[validate(email(message = "..."))]. The same placement applies to every rule, including length, range, and required.

A Table of the Four Attributes

The four attributes side by side make the differences easy to compare.

AttributeWorks onArgumentsWhat it checks
emailString, str, Option of thosenoneThe text is shaped like an email address
lengthString, Vec, Option of thosemin, max, equalThe count of characters or items sits within the limits
rangeintegers, floats, Option of thosemin, max, exclusive_min, exclusive_maxThe number sits within the limits
requiredOption onlynoneThe field holds Some, not None

The pattern in the table is that each attribute matches a kind of value. Shape rules go on text, counting rules go on text and lists, size rules go on numbers, and presence rules go on Option fields. When a derive macro reports a type error, the table is the first place to check: the rule and the field type have to belong together.

What Happens When a Request Arrives

The four attributes slot into the same request flow as before, with one new detail: each rule now knows what text to report when it fails.

JSON arrives
        |
        v
Serde builds the struct
        |
        v
validate() runs email, length, range, required
        |
        v
Every failure carries a code and a message
        |
        v
Handler turns the map into a 422 field-error body

The message written in the attribute is the text that ends up in the response body. That is why messages are worth writing in plain words a user understands, rather than in the language of the rule. "Enter a valid email address" tells the user what to do. The code "email" tells a program what happened. Both travel in the same error entry.

Testing It

Each attribute deserves at least one passing test and one failing test. The tests below check the boundary values, because boundaries are where inclusive and exclusive rules are most often misunderstood.

src/main.rs
use validator::Validate;

#[derive(Debug, Validate)]
struct Signup {
    #[validate(email(message = "enter a valid email address"))]
    email: String,
    #[validate(length(min = 3, max = 30))]
    name: String,
    #[validate(range(min = 18, max = 120))]
    age: u32,
    #[validate(required)]
    nickname: Option<String>,
}

#[cfg(test)]
mod tests {
    use super::*;

    fn signup() -> Signup {
        Signup {
            email: "ada@example.com".to_string(),
            name: "Ada".to_string(),
            age: 30,
            nickname: Some("ada".to_string()),
        }
    }

    #[test]
    fn good_signup_passes() {
        assert!(signup().validate().is_ok());
    }

    #[test]
    fn boundary_values_pass() {
        let mut value = signup();
        value.name = "Ada".to_string();
        value.age = 18;
        assert!(value.validate().is_ok());
        value.age = 120;
        assert!(value.validate().is_ok());
    }

    #[test]
    fn bad_email_fails_with_custom_message() {
        let mut value = signup();
        value.email = "not-an-email".to_string();
        let errors = value.validate().unwrap_err();
        let field = &errors.field_errors()["email"];
        assert_eq!(field[0].code, "email");
        assert_eq!(
            field[0].message.as_deref(),
            Some("enter a valid email address")
        );
    }

    #[test]
    fn short_name_fails() {
        let mut value = signup();
        value.name = "Al".to_string();
        let errors = value.validate().unwrap_err();
        assert!(errors.field_errors().contains_key("name"));
    }

    #[test]
    fn young_age_fails() {
        let mut value = signup();
        value.age = 17;
        let errors = value.validate().unwrap_err();
        assert!(errors.field_errors().contains_key("age"));
    }

    #[test]
    fn missing_nickname_fails() {
        let mut value = signup();
        value.nickname = None;
        let errors = value.validate().unwrap_err();
        assert!(errors.field_errors().contains_key("nickname"));
    }

    #[test]
    fn optional_email_none_passes() {
        #[derive(Debug, Validate)]
        struct Contact {
            #[validate(email)]
            email: Option<String>,
        }
        assert!(Contact { email: None }.validate().is_ok());
        assert!(Contact {
            email: Some("not-an-email".to_string())
        }
        .validate()
        .is_err());
    }
}

The boundary test is the one that catches an off-by-one mistake in a rule. If range(min = 18) were exclusive, the age 18 case would fail and the test would catch it. The custom message test reads the error entry directly and checks both the code and the message, which pins down the exact text the response will carry. The last test pins down the Option behaviour: None skips the email rule, Some with bad text fails it. Run the tests with cargo test and expect seven passes.

Common Beginner Mistakes

Writing message at the Wrong Level

// Wrong - message is not an argument of the attribute itself
#[validate(email, message = "enter a valid email address")]
email: String,

The compiler rejects this with "Unknown field: message". The fix is to move the argument inside the rule's parentheses, as #[validate(email(message = "enter a valid email address"))]. This mistake is common because the attribute and the rule look like the same level, but they are not. The attribute holds rules, and each rule holds its own arguments.

Using length on a Number

// Wrong - numbers have a value, not a length
#[derive(Debug, Validate)]
struct Signup {
    #[validate(length(min = 3))]
    age: u32,
}

The compiler rejects this with a type error, because length only works on strings and lists. The rule that checks a number's size is range. The fix is to swap the attribute: #[validate(range(min = 3))]. The same confusion runs the other way: range on a string fails, because a string has a length, not a numeric value.

Assuming required Checks the Value Inside

// Wrong expectation - required only checks presence
#[derive(Debug, Validate)]
struct Profile {
    #[validate(required)]
    nickname: Option<String>,
}

A Some value holding an empty string passes the required rule, because the field is present. Presence is all the rule checks. If an empty string should also fail, the field needs a second rule for the value inside, such as length(min = 1), written alongside required in the same attribute. The two rules answer two different questions, and one of them cannot answer for the other.

Expecting email to Prove the Address Is Real

// Wrong expectation - "a@b" passes the email rule
let contact = Contact { email: "a@b".to_string() };
assert!(contact.validate().is_ok());

This assertion passes, and it surprises people who expect the rule to demand a full domain. The HTML5 pattern only asks for the shape, and "a@b" has the shape. The fix is not a different attribute. It is a different kind of check, later in the flow, such as sending a confirmation email. The attribute is a shape filter, and treating it as proof of a real mailbox is a design mistake rather than a code mistake.

Final Complete Example

Here is everything from this page put together: a struct with all four attributes, custom messages on every rule, and a main that prints the result for a good value and a bad value.

src/main.rs
use validator::Validate;

#[derive(Debug, Validate)]
struct Signup {
    #[validate(email(message = "enter a valid email address"))]
    email: String,
    #[validate(length(min = 3, max = 30, message = "name must be between 3 and 30 characters"))]
    name: String,
    #[validate(range(min = 18, max = 120, message = "age must be between 18 and 120"))]
    age: u32,
    #[validate(required(message = "nickname is required"))]
    nickname: Option<String>,
}

fn main() {
    let good = Signup {
        email: "ada@example.com".to_string(),
        name: "Ada".to_string(),
        age: 30,
        nickname: Some("ada".to_string()),
    };
    println!("good: {:?}", good.validate());

    let bad = Signup {
        email: "nope".to_string(),
        name: "Al".to_string(),
        age: 200,
        nickname: None,
    };
    println!("bad: {:?}", bad.validate());
}

The good value prints Ok(()). The bad value prints one Err with four entries, and every entry now carries a message a user can act on.

Summary

The four attributes divide the work of checking a struct by the kind of question each field asks. Shape questions go to email, counting questions go to length, size questions go to range, and presence questions go to required, and each rule keeps its own limits and its own message inside its own parentheses. The single most useful habit to take from this page is to read the error entry as two separate pieces of information: the code names the rule for the program, and the message names the fix for the person. A struct written this way already knows everything a good error response needs to say. What remains is the call that runs the rules at the right moment and the code that turns the map into a response, and both of those live in the handler.