Skip to content

Validation

The Basics

Validation

Introduction

Validation lets you check the input your application receives before you use it. For example, a sign-up form should arrive with an email address, and an API client shouldn't be able to order -3 of a product. With Laravel, you describe the input you expect as a Rust struct and put rules on its fields. Your handler only receives the struct once the input passes every rule. If it doesn't, Laravel redirects the user back to the form and shows them what needs fixing. An API client gets a JSON response that lists the errors instead.

Laravel includes rules for text, numbers, dates, formats such as email addresses, files, and database records, and you may write rules of your own. To see how the pieces fit together, let's look at a complete example of validating a form.

Validation quickstart

For example, say your application lets users write blog posts. In src/routes/web.rs, one route shows the form for a new post, and another stores the post once the user submits the form:

1use laravel::prelude::*;
2 
3use crate::http::handlers::posts;
4 
5pub fn routes(route: &mut Router) {
6 route.get("/posts/create", posts::create);
7 route.post("/posts", posts::store);
8}
1use laravel::prelude::*;
2 
3use crate::http::handlers::posts;
4 
5pub fn routes(route: &mut Router) {
6 route.get("/posts/create", posts::create);
7 route.post("/posts", posts::store);
8}

Defining the input

Next, in the module that holds your post handlers, describe the form's input as a struct. Mark the struct with #[laravel::input(fills = Post)], which derives Deserialize and Validate for it and lets you save it to a Post. Then put each field's rules in a #[validate(...)] attribute:

1use laravel::prelude::*;
2 
3use crate::models::Post;
4 
5#[laravel::input(fills = Post)]
6#[validate(anyone)]
7pub struct StorePost {
8 #[validate(required, max_length(255), unique(Post::title))]
9 title: String,
10 #[validate(required)]
11 body: String,
12}
1use laravel::prelude::*;
2 
3use crate::models::Post;
4 
5#[laravel::input(fills = Post)]
6#[validate(anyone)]
7pub struct StorePost {
8 #[validate(required, max_length(255), unique(Post::title))]
9 title: String,
10 #[validate(required)]
11 body: String,
12}

Laravel checks each field's rules in the order you write them. To learn more about the rules you may use, check out the available rules.

#[validate(anyone)] says that anyone who can reach the route may submit the form. Every type you validate from a request must say who may submit it. So a handler that validates a type without anyone, authenticated, or an authorize function doesn't compile. To keep the focus on the rules, the rule examples later on this page leave this attribute out, but your own types need it.

A String field accepts only text, and a number field such as u32 accepts only numbers that fit it, so you don't need rules for the type.

Handling the request

Now take a Valid<T> argument in your store handler. It must be the handler's last argument, because it reads the request's body:

1use laravel::model::create;
2use laravel::prelude::*;
3 
4use crate::models::Post;
5 
6pub async fn store(Valid(form): Valid<StorePost>) -> laravel::Result<Redirect> {
7 let post = create!(Post { ..form }).await?;
8 
9 Ok(redirect!(show, post.id))
10}
1use laravel::model::create;
2use laravel::prelude::*;
3 
4use crate::models::Post;
5 
6pub async fn store(Valid(form): Valid<StorePost>) -> laravel::Result<Redirect> {
7 let post = create!(Post { ..form }).await?;
8 
9 Ok(redirect!(show, post.id))
10}

Your store handler only runs when the input fits the struct and passes every rule. If it doesn't, Laravel sends the user back to the form with the errors, and your handler never runs.

fills = Post makes StorePost a fill struct for the Post model. Each of its fields fills the Post column of the same name, and ..form at the end of create! copies the fields into the new post. A fill struct also lists the only columns a request may write. Laravel ignores any submitted field that the struct doesn't declare, so a user can't add is_admin=1 to the form and change a column you never showed them. To learn more, check out the models guide's section on fill structs.

Valid<T> and Request both read the request's body, so a handler can't take both. If your handler needs the request too, take a ValidRequest<T> as its last argument instead. It validates T as Valid<T> does, and its into_parts method returns the input and the request. For example, if your posts table has an ip_address column for moderating spam, this handler records the address each post came from:

1use laravel::validation::ValidRequest;
2 
3pub async fn store(input: ValidRequest<StorePost>) -> laravel::Result<Redirect> {
4 let (form, request) = input.into_parts();
5 
6 let post = create!(Post { ip_address: request.ip().to_string(), ..form }).await?;
7 
8 Ok(redirect!(show, post.id))
9}
1use laravel::validation::ValidRequest;
2 
3pub async fn store(input: ValidRequest<StorePost>) -> laravel::Result<Redirect> {
4 let (form, request) = input.into_parts();
5 
6 let post = create!(Post { ip_address: request.ip().to_string(), ..form }).await?;
7 
8 Ok(redirect!(show, post.id))
9}

If you only need to read the input, you don't need into_parts. You may read the input's fields through the ValidRequest itself, as in input.title, and its request method returns the request.

Optional fields

If the user may leave a field empty, such as the date a post should be published, declare the field as an Option. Laravel's default TrimStrings and ConvertEmptyStringsToNull middleware turn an empty text input into null before validation runs, and an Option field receives null as None. If the user does fill in the field, the field's other rules still check the value:

1#[laravel::input]
2pub struct StorePost {
3 #[validate(required, max_length(255))]
4 title: String,
5 #[validate(date)]
6 publish_on: Option<laravel::time::civil::Date>,
7}
1#[laravel::input]
2pub struct StorePost {
3 #[validate(required, max_length(255))]
4 title: String,
5 #[validate(date)]
6 publish_on: Option<laravel::time::civil::Date>,
7}

Ordinary rules, such as max_length and date, skip missing fields and blank strings. They skip null only on nullable fields, such as an Option. Add required when an empty value should fail.

Fields a request may leave out

An Option field can't tell a field the request left out from one it sent empty. An HTML form sends every field, so that's usually fine. A JSON PATCH request, or an Inertia form that sends only what changed, leaves out the fields the user didn't touch. There, a missing field typically means "keep the current value", and null means "clear it".

Declare those fields as Sometimes<T>. A field the request leaves out is Sometimes::Missing, and validation skips all of its rules, required included. A field the request sends is Sometimes::Present, and its rules run as usual:

1use laravel::validation::Sometimes;
2 
3#[laravel::input]
4#[validate(authenticated)]
5pub struct EditProfile {
6 #[validate(required, max_length(255))]
7 pub name: Sometimes<String>,
8 #[validate(max_length(1000))]
9 pub bio: Sometimes<Option<String>>,
10}
1use laravel::validation::Sometimes;
2 
3#[laravel::input]
4#[validate(authenticated)]
5pub struct EditProfile {
6 #[validate(required, max_length(255))]
7 pub name: Sometimes<String>,
8 #[validate(max_length(1000))]
9 pub bio: Sometimes<Option<String>>,
10}
The request name bio
Leaves out both fields Missing Missing
Sends name as "Taylor" Present("Taylor") Missing
Sends bio as null or blank Missing Present(None)
Sends name as null or blank Fails: "The name field is required." Missing

So required on a Sometimes field means "not empty, if sent". A Sometimes<String> field that the request sends must hold text, even without required. To let a sent field be empty, declare it Sometimes<Option<String>>, as bio does.

In the handler, match on the field or use its helpers. present() returns the sent value as an Option, is_missing() says whether the request left the field out, and is_null() says whether a Sometimes<Option<T>> field was sent empty. When you save a fill struct to a model, Laravel skips every Missing field, so those columns keep their current values. To learn more, check out the models guide's section on updating only the fields a request sends.

Enum and ID fields

A form often offers a fixed set of choices, such as whether a new post is a draft or published right away. To accept one of those choices, declare the field as your own enum and derive Enum for it, as you would for an enum column. The field then accepts only the variants' Serde names, so with #[serde(rename_all = "snake_case")], visibility=published decodes to Visibility::Published and visibility=archived fails validation:

1use laravel::prelude::*;
2 
3#[derive(Clone, Copy, Debug, Serialize, Deserialize, Enum)]
4#[serde(rename_all = "snake_case")]
5pub enum Visibility {
6 Draft,
7 Published,
8}
9 
10#[laravel::input]
11pub struct StorePost {
12 #[validate(required, max_length(255))]
13 title: String,
14 visibility: Visibility,
15}
1use laravel::prelude::*;
2 
3#[derive(Clone, Copy, Debug, Serialize, Deserialize, Enum)]
4#[serde(rename_all = "snake_case")]
5pub enum Visibility {
6 Draft,
7 Published,
8}
9 
10#[laravel::input]
11pub struct StorePost {
12 #[validate(required, max_length(255))]
13 title: String,
14 visibility: Visibility,
15}

Rules such as one_of and distinct compare a variant by its Serde name, so write one_of("draft") rather than the variant's Rust name.

Some applications wrap IDs in their own types, so a CategoryId can't be passed where a UserId belongs. Derive Newtype for such a wrapper, and the field accepts and validates the same input as the type it wraps:

1#[derive(Clone, Copy, Debug, Deserialize, Newtype)]
2pub struct CategoryId(i64);
3 
4#[laravel::input]
5pub struct StorePost {
6 #[validate(required, max_length(255))]
7 title: String,
8 #[validate(min_value(1))]
9 category_id: CategoryId,
10}
1#[derive(Clone, Copy, Debug, Deserialize, Newtype)]
2pub struct CategoryId(i64);
3 
4#[laravel::input]
5pub struct StorePost {
6 #[validate(required, max_length(255))]
7 title: String,
8 #[validate(min_value(1))]
9 category_id: CategoryId,
10}

Transforming input fields

Sometimes you'll want to normalize a field's casing before you validate or store it, such as lowercasing email addresses so database unique indexes match regardless of how the user typed them, or uppercasing country and coupon codes. You may add #[transform(lowercase)] or #[transform(uppercase)] to any string field on an input or query struct:

1use laravel::prelude::*;
2 
3use crate::models::User;
4 
5#[laravel::input(fills = User)]
6#[validate(anyone)]
7pub struct RegisterUser {
8 #[validate(required, max_length(255))]
9 name: String,
10 #[transform(lowercase)]
11 #[validate(required, email, unique(User::email))]
12 email: String,
13 #[transform(uppercase)]
14 #[validate(required, min_length(2), max_length(2))]
15 country: String,
16}
1use laravel::prelude::*;
2 
3use crate::models::User;
4 
5#[laravel::input(fills = User)]
6#[validate(anyone)]
7pub struct RegisterUser {
8 #[validate(required, max_length(255))]
9 name: String,
10 #[transform(lowercase)]
11 #[validate(required, email, unique(User::email))]
12 email: String,
13 #[transform(uppercase)]
14 #[validate(required, min_length(2), max_length(2))]
15 country: String,
16}

Laravel runs #[transform(..)] as soon as the request binds into the struct, before validation rules, dynamic rules hooks, and your handler see the value. If a user submits [email protected], the unique rule queries the database for [email protected], and your handler receives [email protected]. When a browser form fails validation, old input keeps what the user originally typed.

#[transform(..)] works on String fields, Newtype wrappers around String, and Option, Sometimes, Box, Vec, set, and map fields that hold strings. It applies across Valid<T>, ValidRequest<T>, request.parse(), request.json(), and Query<T>. To transform a field across every request regardless of which struct binds it, use a middleware with transform_input instead.

Stopping on a field's first failure

Sometimes you'll want to stop checking a field after its first failure, such as to skip a database query for a title that's already too long. To do so, add bail to the field's rules. In this example, if the title is longer than 255 characters, the unique rule never queries the database:

1#[validate(bail, required, max_length(255), unique(Post::title))]
2title: String,
1#[validate(bail, required, max_length(255), unique(Post::title))]
2title: String,

bail stops only its own field. Other fields keep validating, so the user still sees every field that needs fixing. When a presence rule such as required fails, Laravel skips the rest of that field's rules even without bail.

Validation responses

When validation fails, Laravel responds based on the kind of request:

  • A browser form on a route in the web group gets a redirect back to the previous page. The errors and the submitted input go in the session, so the form can show them.
  • An Inertia form gets the same redirect, and the page receives the errors in its errors prop.
  • A request that expects JSON, or a route in the api group, gets a 422 Unprocessable Content with the errors as JSON.
  • A browser request to a route without a session can't carry errors through a redirect, so it gets the 422 error page.

The JSON response has a message with the first error and a count of the rest, and an errors object with each field's messages. Nested fields use dots in their keys:

1{
2 "message": "The title field is required. (and 1 more error)",
3 "errors": {
4 "title": ["The title field is required."],
5 "author.name": ["The author.name field is required."]
6 }
7}
1{
2 "message": "The title field is required. (and 1 more error)",
3 "errors": {
4 "title": ["The title field is required."],
5 "author.name": ["The author.name field is required."]
6 }
7}

Displaying errors and old input

When validation fails on a web route, Laravel redirects the user back with the validation errors so your page can display them next to each field or in a summary above the form.

Inertia

If your application uses Inertia, Laravel populates the page's errors prop automatically while keeping the user's input intact. Inertia's <Form> component exposes errors through its render prop, so you can show an individual field's message or loop through every error on the form:

1import { Form } from "@inertiajs/react";
2 
3export default function CreatePost() {
4 return (
5 <Form action="/posts" method="post">
6 {({ errors }) => (
7 <>
8 {Object.keys(errors).length > 0 && (
9 <ul className="errors">
10 {Object.entries(errors).map(([field, message]) => (
11 <li key={field}>{message}</li>
12 ))}
13 </ul>
14 )}
15 
16 <label htmlFor="title">Title</label>
17 <input id="title" name="title" />
18 {errors.title && <p className="error">{errors.title}</p>}
19 </>
20 )}
21 </Form>
22 );
23}
1import { Form } from "@inertiajs/react";
2 
3export default function CreatePost() {
4 return (
5 <Form action="/posts" method="post">
6 {({ errors }) => (
7 <>
8 {Object.keys(errors).length > 0 && (
9 <ul className="errors">
10 {Object.entries(errors).map(([field, message]) => (
11 <li key={field}>{message}</li>
12 ))}
13 </ul>
14 )}
15 
16 <label htmlFor="title">Title</label>
17 <input id="title" name="title" />
18 {errors.title && <p className="error">{errors.title}</p>}
19 </>
20 )}
21 </Form>
22 );
23}

MiniJinja

When rendering server-side templates with MiniJinja, Laravel flashes the errors and the submitted input to the session for the next request. Use error to read a field's first error and old to fill the field back in with what the user typed, passing a default value as the second argument for the initial render:

1<!-- resources/views/posts/create.html -->
2 
3<label for="title">Title</label>
4<input id="title" name="title" value="{{ old('title', '') }}">
5 
6{% if error('title') %}
7 <p class="error">{{ error('title') }}</p>
8{% endif %}
1<!-- resources/views/posts/create.html -->
2 
3<label for="title">Title</label>
4<input id="title" name="title" value="{{ old('title', '') }}">
5 
6{% if error('title') %}
7 <p class="error">{{ error('title') }}</p>
8{% endif %}

Your views also receive every error in an errors map, keyed by field, so errors.title holds all of the title's messages. To list every message above the form, loop over the map:

1{% if errors %}
2 <ul class="errors">
3 {% for field, messages in errors|items %}
4 {% for message in messages %}
5 <li>{{ message }}</li>
6 {% endfor %}
7 {% endfor %}
8 </ul>
9{% endif %}
1{% if errors %}
2 <ul class="errors">
3 {% for field, messages in errors|items %}
4 {% for message in messages %}
5 <li>{{ message }}</li>
6 {% endfor %}
7 {% endfor %}
8 </ul>
9{% endif %}

To see a complete form that shows its errors, check out the templates guide's section on validation errors and old input.

If you need old input in a handler, request.old::<String>("title") returns the submitted value as the type you name. It accepts dotted paths, such as author.name, and returns None when the field wasn't submitted or isn't that type.

Old input never includes passwords or uploaded files, so the user enters those again. Laravel leaves out every Password field of the validated type, and any field named password, password_confirmation, or current_password. To keep other fields out of the session, list them with dont_flash.

Pages with several forms

When a page has two forms with the same field, such as a login form and a registration form that both have an email field, name each form on its input type to keep its errors apart:

1use laravel::hash::Password;
2 
3#[laravel::input]
4#[validate(anyone, form = "login")]
5pub struct Login {
6 #[validate(required, email)]
7 email: String,
8 #[validate(required)]
9 password: Password,
10}
1use laravel::hash::Password;
2 
3#[laravel::input]
4#[validate(anyone, form = "login")]
5pub struct Login {
6 #[validate(required, email)]
7 email: String,
8 #[validate(required)]
9 password: Password,
10}

Inertia

Inertia pages receive a named form's errors under its name, such as errors.login.email. Pass errorBag to <Form> so its errors render prop is scoped to that form automatically:

1import { Form } from "@inertiajs/react";
2 
3export default function LoginForm() {
4 return (
5 <Form action="/login" method="post" errorBag="login">
6 {({ errors }) => (
7 <>
8 {Object.keys(errors).length > 0 && (
9 <ul className="errors">
10 {Object.entries(errors).map(([field, message]) => (
11 <li key={field}>{message}</li>
12 ))}
13 </ul>
14 )}
15 
16 <label htmlFor="email">Email</label>
17 <input id="email" name="email" type="email" />
18 {errors.email && <p className="error">{errors.email}</p>}
19 </>
20 )}
21 </Form>
22 );
23}
1import { Form } from "@inertiajs/react";
2 
3export default function LoginForm() {
4 return (
5 <Form action="/login" method="post" errorBag="login">
6 {({ errors }) => (
7 <>
8 {Object.keys(errors).length > 0 && (
9 <ul className="errors">
10 {Object.entries(errors).map(([field, message]) => (
11 <li key={field}>{message}</li>
12 ))}
13 </ul>
14 )}
15 
16 <label htmlFor="email">Email</label>
17 <input id="email" name="email" type="email" />
18 {errors.email && <p className="error">{errors.email}</p>}
19 </>
20 )}
21 </Form>
22 );
23}

MiniJinja

In a MiniJinja template, pass the form's name to error to read that form's messages. The errors map only holds the errors of forms without a name:

1{% if error("email", form="login") %}
2 <p class="error">{{ error("email", form="login") }}</p>
3{% endif %}
1{% if error("email", form="login") %}
2 <p class="error">{{ error("email", form="login") }}</p>
3{% endif %}

Every named form's errors are also in form_errors, keyed by form name. Use form_errors.login to list all errors for the login form, or form_errors.login.email to list one field's messages:

1{% if form_errors.login %}
2 <ul class="errors">
3 {% for field, messages in form_errors.login|items %}
4 {% for message in messages %}
5 <li>{{ message }}</li>
6 {% endfor %}
7 {% endfor %}
8 </ul>
9{% endif %}
1{% if form_errors.login %}
2 <ul class="errors">
3 {% for field, messages in form_errors.login|items %}
4 {% for message in messages %}
5 <li>{{ message }}</li>
6 {% endfor %}
7 {% endfor %}
8 </ul>
9{% endif %}

Scoping handler errors

Errors that your handler returns after validation, such as with invalid!, are automatically scoped to the same named form. For example, because this handler accepts Valid<Login>, when auth.attempt rejects invalid credentials, the error appears under errors.login.email in Inertia pages and error("email", form="login") in MiniJinja templates:

1use laravel::auth::Auth;
2use laravel::prelude::*;
3 
4pub async fn login(
5 auth: Auth<User>,
6 Valid(form): Valid<Login>,
7) -> laravel::Result<Redirect> {
8 auth.attempt(&form.email, &form.password).await?;
9 
10 Ok(Redirect::intended(dashboard::show, ()))
11}
1use laravel::auth::Auth;
2use laravel::prelude::*;
3 
4pub async fn login(
5 auth: Auth<User>,
6 Valid(form): Valid<Login>,
7) -> laravel::Result<Redirect> {
8 auth.attempt(&form.email, &form.password).await?;
9 
10 Ok(Redirect::intended(dashboard::show, ()))
11}

When several forms on a page submit the same input type, such as a reply form under each comment, name each form with a hidden _form field instead, as in <input type="hidden" name="_form" value="reply-7">. If a request sends a _form field for a type that also has a name, Laravel uses the _form field's name.

Authorization and rules from the request

Sometimes a form needs more than rules. For example, a form that renames a team should check that the user may rename it, and a rule might depend on who's asking. To keep that logic next to the form's rules, rather than in every handler that takes the form, implement ValidatesRequest on the input type.

ValidatesRequest has two functions. authorize decides who may submit the type, and rules adds rules that depend on the request. Valid<T> runs both before your handler. Say each User has an is_admin flag and an is_premium plan. Only admins may rename their team, and premium teams get longer names:

1use laravel::prelude::*;
2use laravel::validation::{Rule, Rules, ValidatesRequest};
3 
4#[laravel::input]
5pub struct UpdateTeam {
6 #[validate(required, max_length(255))]
7 name: String,
8}
9 
10impl ValidatesRequest for UpdateTeam {
11 async fn authorize(request: &Request) -> laravel::Result<bool> {
12 let admin = request
13 .user::<User>()
14 .await?
15 .is_some_and(|user| user.is_admin);
16 
17 Ok(admin)
18 }
19 
20 async fn rules(&self, request: &Request, rules: Rules) -> laravel::Result<Rules> {
21 let premium = request
22 .user::<User>()
23 .await?
24 .is_some_and(|user| user.is_premium);
25 
26 Ok(rules.field("name", [Rule::max_length(if premium { 255 } else { 50 })]))
27 }
28}
29 
30pub async fn update(Valid(team): Valid<UpdateTeam>) -> laravel::Result<Redirect> {
31 // Only admins get here, with a name that fits their plan...
32 
33 Ok(Redirect::back())
34}
1use laravel::prelude::*;
2use laravel::validation::{Rule, Rules, ValidatesRequest};
3 
4#[laravel::input]
5pub struct UpdateTeam {
6 #[validate(required, max_length(255))]
7 name: String,
8}
9 
10impl ValidatesRequest for UpdateTeam {
11 async fn authorize(request: &Request) -> laravel::Result<bool> {
12 let admin = request
13 .user::<User>()
14 .await?
15 .is_some_and(|user| user.is_admin);
16 
17 Ok(admin)
18 }
19 
20 async fn rules(&self, request: &Request, rules: Rules) -> laravel::Result<Rules> {
21 let premium = request
22 .user::<User>()
23 .await?
24 .is_some_and(|user| user.is_premium);
25 
26 Ok(rules.field("name", [Rule::max_length(if premium { 255 } else { 50 })]))
27 }
28}
29 
30pub async fn update(Valid(team): Valid<UpdateTeam>) -> laravel::Result<Redirect> {
31 // Only admins get here, with a name that fits their plan...
32 
33 Ok(Redirect::back())
34}

authorize is required, and rules is optional. If you leave out rules, Laravel validates with the rules declared on the struct's fields. When you do write rules, its rules argument already holds the rules declared on the struct. Calling rules.field("name", ..) adds more rules to the name field rather than replacing the ones it has. So in this example, a team's name must still pass required and max_length(255) from the struct, and then the limit for the user's plan.

Only the struct your handler validates needs ValidatesRequest. A nested struct or list item always uses the rules declared on its own fields. For example, if the team form also takes the team's billing address, only UpdateTeam implements ValidatesRequest. Laravel checks billing_address with the rules on Address's fields:

1#[laravel::input]
2pub struct UpdateTeam {
3 #[validate(required, max_length(255))]
4 name: String,
5 billing_address: Address,
6}
7 
8#[laravel::input]
9pub struct Address {
10 #[validate(required, max_length(255))]
11 street: String,
12 #[validate(required)]
13 city: String,
14}
1#[laravel::input]
2pub struct UpdateTeam {
3 #[validate(required, max_length(255))]
4 name: String,
5 billing_address: Address,
6}
7 
8#[laravel::input]
9pub struct Address {
10 #[validate(required, max_length(255))]
11 street: String,
12 #[validate(required)]
13 city: String,
14}

Authorizing the request

authorize runs before validation. If it returns false, the request fails with a 403 and the message "This action is unauthorized.", and Laravel doesn't validate the input.

To tell the user why you rejected the request, abort with your own message instead of returning false:

1async fn authorize(request: &Request) -> laravel::Result<bool> {
2 let admin = request
3 .user::<User>()
4 .await?
5 .is_some_and(|user| user.is_admin);
6 
7 if !admin {
8 laravel::abort!(403, "Only team admins can rename a team.");
9 }
10 
11 Ok(true)
12}
1async fn authorize(request: &Request) -> laravel::Result<bool> {
2 let admin = request
3 .user::<User>()
4 .await?
5 .is_some_and(|user| user.is_admin);
6 
7 if !admin {
8 laravel::abort!(403, "Only team admins can rename a team.");
9 }
10 
11 Ok(true)
12}

You may skip writing authorize for the two most common answers:

  • #[validate(anyone)] lets anyone submit the form, such as a contact form or a login form.
  • #[validate(authenticated)] lets any logged-in user submit it, such as a change-password form. A guest gets the same response as from the Authenticate middleware: a redirect to the login page, or a 401 for a request that expects JSON.
1#[laravel::input]
2#[validate(authenticated)]
3pub struct UpdateProfile {
4 #[validate(required, max_length(255))]
5 name: String,
6}
1#[laravel::input]
2#[validate(authenticated)]
3pub struct UpdateProfile {
4 #[validate(required, max_length(255))]
5 name: String,
6}

If a type needs a rules function too, implement ValidatesRequest yourself instead of using these attributes. For a form that any logged-in user may submit, have authorize return request.authenticated():

1impl ValidatesRequest for UpdateProfile {
2 async fn authorize(request: &Request) -> laravel::Result<bool> {
3 Ok(request.authenticated().await?)
4 }
5 
6 async fn rules(&self, request: &Request, rules: Rules) -> laravel::Result<Rules> {
7 // Add rules that depend on the request...
8 
9 Ok(rules)
10 }
11}
1impl ValidatesRequest for UpdateProfile {
2 async fn authorize(request: &Request) -> laravel::Result<bool> {
3 Ok(request.authenticated().await?)
4 }
5 
6 async fn rules(&self, request: &Request, rules: Rules) -> laravel::Result<Rules> {
7 // Add rules that depend on the request...
8 
9 Ok(rules)
10 }
11}

When authorize returns false, a guest gets a 403 rather than a redirect to your login page. If guests should be sent to log in, attach the Authenticate middleware to the form's route.

Authorizing with a policy

When a policy decides who may submit a form, name the policy method instead of writing authorize. For each record the method takes, pass route("...") with the route parameter that names the record:

1use crate::policies::PostPolicy;
2 
3#[laravel::input]
4#[validate(authorize(PostPolicy::update, route("post")))]
5pub struct UpdatePost {
6 #[validate(required, max_length(255))]
7 title: String,
8}
1use crate::policies::PostPolicy;
2 
3#[laravel::input]
4#[validate(authorize(PostPolicy::update, route("post")))]
5pub struct UpdatePost {
6 #[validate(required, max_length(255))]
7 title: String,
8}

On a route such as PUT /posts/{post}, Laravel finds the post and checks PostPolicy::update for the current user. A denial gets the policy's response, such as a 403 with its message. For a method without a record, leave out the arguments, as in authorize(PostPolicy::create). To learn more, check out the authorization guide's section on authorizing a form.

Adding rules from the request

Sometimes a rule needs a record that the URL names. For example, say customers order a product at POST /products/{product}/orders, and each Product has a stock column. An order shouldn't ask for more than the product has in stock. To find the product in your rules function, call request.model with the route parameter's name:

1use laravel::prelude::*;
2use laravel::validation::{Rule, Rules, ValidatesRequest};
3 
4use crate::models::Product;
5 
6#[laravel::input]
7pub struct StoreOrder {
8 #[validate(required, min_value(1))]
9 quantity: u32,
10}
11 
12impl ValidatesRequest for StoreOrder {
13 async fn authorize(request: &Request) -> laravel::Result<bool> {
14 Ok(request.authenticated().await?)
15 }
16 
17 async fn rules(&self, request: &Request, rules: Rules) -> laravel::Result<Rules> {
18 let product: Product = request.model("product").await?;
19 
20 Ok(rules.field("quantity", [Rule::max_value(product.stock)]))
21 }
22}
1use laravel::prelude::*;
2use laravel::validation::{Rule, Rules, ValidatesRequest};
3 
4use crate::models::Product;
5 
6#[laravel::input]
7pub struct StoreOrder {
8 #[validate(required, min_value(1))]
9 quantity: u32,
10}
11 
12impl ValidatesRequest for StoreOrder {
13 async fn authorize(request: &Request) -> laravel::Result<bool> {
14 Ok(request.authenticated().await?)
15 }
16 
17 async fn rules(&self, request: &Request, rules: Rules) -> laravel::Result<Rules> {
18 let product: Product = request.model("product").await?;
19 
20 Ok(rules.field("quantity", [Rule::max_value(product.stock)]))
21 }
22}

If no product has the ID in the URL, the request gets a 404. Laravel finds the product once per request, so your handler may also take a product: Product argument without another query.

Because Laravel decodes the input into your struct before calling rules, you may also inspect fields on self when choosing which rules to add. For example, a webhook form might require an HTTPS URL for HTTP webhooks and an identifier for queue webhooks:

1use laravel::prelude::*;
2use laravel::validation::{Rule, Rules, ValidatesRequest};
3 
4#[laravel::input]
5pub struct StoreWebhook {
6 #[validate(required, one_of("http", "queue"))]
7 kind: String,
8 #[validate(required)]
9 target: String,
10}
11 
12impl ValidatesRequest for StoreWebhook {
13 async fn authorize(request: &Request) -> laravel::Result<bool> {
14 Ok(request.authenticated().await?)
15 }
16 
17 async fn rules(&self, _request: &Request, rules: Rules) -> laravel::Result<Rules> {
18 if self.kind == "http" {
19 Ok(rules.field("target", [Rule::url(["https"])]))
20 } else {
21 Ok(rules.field("target", [Rule::alpha_dash()]))
22 }
23 }
24}
1use laravel::prelude::*;
2use laravel::validation::{Rule, Rules, ValidatesRequest};
3 
4#[laravel::input]
5pub struct StoreWebhook {
6 #[validate(required, one_of("http", "queue"))]
7 kind: String,
8 #[validate(required)]
9 target: String,
10}
11 
12impl ValidatesRequest for StoreWebhook {
13 async fn authorize(request: &Request) -> laravel::Result<bool> {
14 Ok(request.authenticated().await?)
15 }
16 
17 async fn rules(&self, _request: &Request, rules: Rules) -> laravel::Result<Rules> {
18 if self.kind == "http" {
19 Ok(rules.field("target", [Rule::url(["https"])]))
20 } else {
21 Ok(rules.field("target", [Rule::alpha_dash()]))
22 }
23 }
24}

Validating in a handler

Most handlers take Valid<T>. If you'd like to decide what happens when validation fails, take the Request instead and call request.validate::<T>(). If you use ? on its result, Laravel redirects a browser back to the form with the errors and the user's input, and gives an API client a 422 JSON response that lists the errors:

1use laravel::prelude::*;
2 
3pub async fn store(request: Request) -> laravel::Result<Redirect> {
4 let form: StorePost = request.validate().await?;
5 
6 // Store the post...
7 
8 Ok(Redirect::back())
9}
1use laravel::prelude::*;
2 
3pub async fn store(request: Request) -> laravel::Result<Redirect> {
4 let form: StorePost = request.validate().await?;
5 
6 // Store the post...
7 
8 Ok(Redirect::back())
9}

To send your own response instead, match on the ValidationError. For example, on a page that swaps the form in place without reloading, this handler returns only the form's template fragment. The fragment shows the errors and keeps what the user typed through with_input, and the response has a 422 status:

1use laravel::prelude::*;
2use laravel::validation::ValidationError;
3 
4pub async fn store(request: Request) -> laravel::Result<Response> {
5 let form = match request.validate::<StorePost>().await {
6 Ok(form) => form,
7 Err(ValidationError::Invalid(errors)) => {
8 return Ok(view("posts.create", data! {})
9 .with_errors(errors)
10 .with_input(&request)
11 .fragment("form")
12 .with_status(StatusCode::UNPROCESSABLE_ENTITY)
13 .into_response());
14 }
15 Err(ValidationError::Failed(error)) => return Err(error),
16 };
17 
18 // Store the post...
19 
20 Ok(redirect!(index).into_response())
21}
1use laravel::prelude::*;
2use laravel::validation::ValidationError;
3 
4pub async fn store(request: Request) -> laravel::Result<Response> {
5 let form = match request.validate::<StorePost>().await {
6 Ok(form) => form,
7 Err(ValidationError::Invalid(errors)) => {
8 return Ok(view("posts.create", data! {})
9 .with_errors(errors)
10 .with_input(&request)
11 .fragment("form")
12 .with_status(StatusCode::UNPROCESSABLE_ENTITY)
13 .into_response());
14 }
15 Err(ValidationError::Failed(error)) => return Err(error),
16 };
17 
18 // Store the post...
19 
20 Ok(redirect!(index).into_response())
21}

ValidationError::Invalid holds the field errors. ValidationError::Failed holds an error that stopped validation, such as a database outage in a unique rule. Return it with ? so that your error handler reports it.

Adding errors after validation

Rules check one field at a time, so they can't express every piece of your application's business logic. For example, whether a hotel room is free depends on both of the dates a guest picked and on the bookings already in your database.

For checks like that, validate what the rules can, then do the rest in your handler. If the input fails your check, return an error for the field with invalid!. The user gets the same response as a failed validation: a redirect back to the form with the errors and the user's input, or a 422 JSON response for an API client:

1use laravel::prelude::*;
2use laravel::time::civil::Date;
3use laravel::validation::invalid;
4 
5use crate::models::{Booking, Room};
6 
7#[laravel::input]
8#[validate(authenticated)]
9pub struct StoreBooking {
10 #[validate(required, exists(Room::id))]
11 room_id: i64,
12 #[validate(required, label = "arrival date")]
13 starts_on: Date,
14 #[validate(required, after(starts_on), label = "departure date")]
15 ends_on: Date,
16}
17 
18pub async fn store(Valid(form): Valid<StoreBooking>) -> laravel::Result<Redirect> {
19 let taken = Booking::query()
20 .filter(Booking::room_id.eq(form.room_id))
21 .filter(Booking::starts_on.lt(form.ends_on))
22 .filter(Booking::ends_on.gt(form.starts_on))
23 .exists()
24 .await?;
25 
26 if taken {
27 invalid!(starts_on => "The room is already booked for some of those dates.");
28 }
29 
30 // Store the booking...
31 
32 Ok(redirect!(bookings::index))
33}
1use laravel::prelude::*;
2use laravel::time::civil::Date;
3use laravel::validation::invalid;
4 
5use crate::models::{Booking, Room};
6 
7#[laravel::input]
8#[validate(authenticated)]
9pub struct StoreBooking {
10 #[validate(required, exists(Room::id))]
11 room_id: i64,
12 #[validate(required, label = "arrival date")]
13 starts_on: Date,
14 #[validate(required, after(starts_on), label = "departure date")]
15 ends_on: Date,
16}
17 
18pub async fn store(Valid(form): Valid<StoreBooking>) -> laravel::Result<Redirect> {
19 let taken = Booking::query()
20 .filter(Booking::room_id.eq(form.room_id))
21 .filter(Booking::starts_on.lt(form.ends_on))
22 .filter(Booking::ends_on.gt(form.starts_on))
23 .exists()
24 .await?;
25 
26 if taken {
27 invalid!(starts_on => "The room is already booked for some of those dates.");
28 }
29 
30 // Store the booking...
31 
32 Ok(redirect!(bookings::index))
33}

To add an error to a nested field with invalid!, write the field's path in "dot" notation, either as a quoted literal such as "items.0.quantity" or a string expression such as format!("items.{index}.quantity"). To give a field several messages, pass a list:

1invalid!(
2 password => ["The password is too common.", "The password appeared in a data breach."],
3 "items.0.quantity" => "Only 3 are left in stock.",
4 format!("members.{index}.user_id") => "This user is already a member.",
5);
1invalid!(
2 password => ["The password is too common.", "The password appeared in a data breach."],
3 "items.0.quantity" => "Only 3 are left in stock.",
4 format!("members.{index}.user_id") => "This user is already a member.",
5);

If you'd like to collect errors as you go, build an InvalidInput and call add with a field's name and a message for each problem you find. When you return the errors from a handler, Laravel redirects the user back to the form with every error you added, or gives an API client a 422 JSON response that lists them.

For example, this handler checks each item of an order against the stock of its product:

1use laravel::validation::InvalidInput;
2 
3use crate::models::Product;
4 
5pub async fn store(Valid(order): Valid<StoreOrder>) -> laravel::Result<Redirect> {
6 let mut errors = InvalidInput::new();
7 
8 for (index, item) in order.items.iter().enumerate() {
9 let product = Product::find_or_fail(item.product_id).await?;
10 
11 if i64::from(item.quantity) > product.stock {
12 errors.add(
13 format!("items.{index}.quantity"),
14 format!("Only {} are left in stock.", product.stock),
15 );
16 }
17 }
18 
19 if !errors.is_empty() {
20 return Err(errors.into());
21 }
22 
23 // Store the order...
24 
25 Ok(redirect!(orders::index))
26}
1use laravel::validation::InvalidInput;
2 
3use crate::models::Product;
4 
5pub async fn store(Valid(order): Valid<StoreOrder>) -> laravel::Result<Redirect> {
6 let mut errors = InvalidInput::new();
7 
8 for (index, item) in order.items.iter().enumerate() {
9 let product = Product::find_or_fail(item.product_id).await?;
10 
11 if i64::from(item.quantity) > product.stock {
12 errors.add(
13 format!("items.{index}.quantity"),
14 format!("Only {} are left in stock.", product.stock),
15 );
16 }
17 }
18 
19 if !errors.is_empty() {
20 return Err(errors.into());
21 }
22 
23 // Store the order...
24 
25 Ok(redirect!(orders::index))
26}

To send the user somewhere other than back to the form, such as to their cart, redirect with the errors yourself:

1return Ok(redirect!(cart::show).with_errors(errors));
1return Ok(redirect!(cart::show).with_errors(errors));

On a page with several forms, errors you add are automatically scoped to the same form as validation errors. Laravel uses the submitted _form name when present, or falls back to the type's #[validate(form = "...")] name. This applies whether you return the errors directly or attach them to a redirect or view. To target a different form instead, call errors.for_form("register").

Validating outside a request

Sometimes you'll need to check data that didn't come from a request, such as each row of a CSV file that a console command imports. Derive Validate on a struct to declare the row's rules, build the struct, and call validate:

1use laravel::validation::{Validate, ValidationError};
2 
3#[derive(Validate)]
4struct ImportedPost {
5 #[validate(required, max_length(255))]
6 title: String,
7 #[validate(required)]
8 body: String,
9}
10 
11pub async fn import_row(row: &[String]) -> laravel::Result<()> {
12 let post = ImportedPost {
13 title: row[0].clone(),
14 body: row[1].clone(),
15 };
16 
17 match post.validate().await {
18 Ok(()) => {
19 // Store the post...
20 }
21 Err(ValidationError::Invalid(errors)) => {
22 for (field, messages) in errors.errors() {
23 for message in messages {
24 println!("{field}: {message}");
25 }
26 }
27 }
28 Err(ValidationError::Failed(error)) => return Err(error),
29 }
30 
31 Ok(())
32}
1use laravel::validation::{Validate, ValidationError};
2 
3#[derive(Validate)]
4struct ImportedPost {
5 #[validate(required, max_length(255))]
6 title: String,
7 #[validate(required)]
8 body: String,
9}
10 
11pub async fn import_row(row: &[String]) -> laravel::Result<()> {
12 let post = ImportedPost {
13 title: row[0].clone(),
14 body: row[1].clone(),
15 };
16 
17 match post.validate().await {
18 Ok(()) => {
19 // Store the post...
20 }
21 Err(ValidationError::Invalid(errors)) => {
22 for (field, messages) in errors.errors() {
23 for message in messages {
24 println!("{field}: {message}");
25 }
26 }
27 }
28 Err(ValidationError::Failed(error)) => return Err(error),
29 }
30 
31 Ok(())
32}

validate checks the struct's fields as any other Validate struct does. Inside a handler returning laravel::Result, you may propagate post.validate().await? directly with ?, and Laravel turns ValidationError::Invalid into a 422 JSON response for API requests or a redirect back with the errors for browser requests. Derive Fill alongside Validate with #[fills(Post)] to pass the validated struct straight to create! or update!:

1use laravel::model::{Fill, create};
2use laravel::prelude::*;
3use laravel::validation::Validate;
4 
5use crate::models::{Post, User};
6 
7#[derive(Validate, Fill)]
8#[fills(Post)]
9struct ImportedPost {
10 #[validate(required, max_length(255))]
11 title: String,
12 #[validate(required)]
13 body: String,
14}
15 
16pub async fn import(Authenticated(user): Authenticated<User>) -> laravel::Result<Redirect> {
17 let input = ImportedPost {
18 title: "Imported post".into(),
19 body: "Post contents...".into(),
20 };
21 
22 input.validate().await?;
23 
24 let post = create!(Post { user: &user, ..input }).await?;
25 
26 Ok(redirect!(posts::show, &post))
27}
1use laravel::model::{Fill, create};
2use laravel::prelude::*;
3use laravel::validation::Validate;
4 
5use crate::models::{Post, User};
6 
7#[derive(Validate, Fill)]
8#[fills(Post)]
9struct ImportedPost {
10 #[validate(required, max_length(255))]
11 title: String,
12 #[validate(required)]
13 body: String,
14}
15 
16pub async fn import(Authenticated(user): Authenticated<User>) -> laravel::Result<Redirect> {
17 let input = ImportedPost {
18 title: "Imported post".into(),
19 body: "Post contents...".into(),
20 };
21 
22 input.validate().await?;
23 
24 let post = create!(Post { user: &user, ..input }).await?;
25 
26 Ok(redirect!(posts::show, &post))
27}

To learn more about Fill structs, check out the models guide's section on fill structs.

Filters that ignore bad values

A list page often reads its filters from the query string, as in /issues?priority=high&assignee=7. Users bookmark and share those URLs, so a filter may arrive with a value that's no longer valid. Redirecting back doesn't help a user who opened a bookmark, because there's no previous page with a form to show the error on. It's better to drop the bad filter and show the list.

Mark your filter struct with #[laravel::query] and extract it with Query<T>. Every field with a fallback (Option<T>, #[default], or #[default = value]) is lenient: if a parameter is blank, doesn't decode (such as an unknown enum value or assignee=abc for an i64), or fails its #[validate(..)] rules, Laravel drops that field and uses its fallback while keeping the rest:

1use laravel::inertia::{self, Page, props};
2use laravel::prelude::*;
3 
4#[derive(Deserialize, Serialize, Enum)]
5#[serde(rename_all = "snake_case")]
6pub enum Priority {
7 Low,
8 High,
9}
10 
11#[laravel::query]
12#[derive(Serialize)]
13pub struct IssueFilters {
14 priority: Option<Priority>,
15 assignee: Option<i64>,
16 #[default]
17 #[validate(max_length(100))]
18 q: String,
19 #[default = 1]
20 #[validate(min_value(1))]
21 page: u32,
22 #[default]
23 labels: Vec<i64>,
24}
25 
26pub async fn index(Query(filters): Query<IssueFilters>) -> Page {
27 // Query the issues that match the filters...
28 
29 inertia::render("Issues/Index", props! { filters })
30}
1use laravel::inertia::{self, Page, props};
2use laravel::prelude::*;
3 
4#[derive(Deserialize, Serialize, Enum)]
5#[serde(rename_all = "snake_case")]
6pub enum Priority {
7 Low,
8 High,
9}
10 
11#[laravel::query]
12#[derive(Serialize)]
13pub struct IssueFilters {
14 priority: Option<Priority>,
15 assignee: Option<i64>,
16 #[default]
17 #[validate(max_length(100))]
18 q: String,
19 #[default = 1]
20 #[validate(min_value(1))]
21 page: u32,
22 #[default]
23 labels: Vec<i64>,
24}
25 
26pub async fn index(Query(filters): Query<IssueFilters>) -> Page {
27 // Query the issues that match the filters...
28 
29 inertia::render("Issues/Index", props! { filters })
30}

/issues?priority=bogus&assignee=7&page=0 reaches the handler with priority as None, assignee as Some(7), and page as 1. Fields without Option or #[default] stay required and respond with 400 Bad Request when missing or invalid. To learn more, check out query string input.

The handler passes the filters back to the page, so the page can show which ones are applied. Inertia sends props to the browser as JSON, so IssueFilters and Priority also derive Serialize.

Available rules

The sections below list every rule Laravel includes, grouped by the kind of value each rule checks. Each section's table shows the rules as you'd write them in a field's #[validate(...)] attribute, which is where you'll usually put them:

1#[laravel::input]
2pub struct StorePost {
3 #[validate(required, max_length(100))]
4 title: String,
5 #[validate(required, one_of("draft", "published"))]
6 status: String,
7}
1#[laravel::input]
2pub struct StorePost {
3 #[validate(required, max_length(100))]
4 title: String,
5 #[validate(required, one_of("draft", "published"))]
6 status: String,
7}

When you add rules in code instead, such as in a rules function, each rule has a Rule constructor with the same name. A rule that takes several values, such as one_of, takes them as an array:

1rules
2 .field("title", [Rule::required(), Rule::max_length(100)])
3 .field("status", [Rule::required(), Rule::one_of(["draft", "published"])])
1rules
2 .field("title", [Rule::required(), Rule::max_length(100)])
3 .field("status", [Rule::required(), Rule::one_of(["draft", "published"])])

Most rules skip missing fields and blank strings. Add required to a field that must have a value.

Text and choices

Attribute Passes when the value is
string Text. String fields have this rule already
min_length(3) Text of at least 3 characters
max_length(255) Text of at most 255 characters
one_of("draft", "published") One of the choices
not_one_of("admin", "root") None of the choices
confirmed The same as the <name>_confirmation field, such as password_confirmation
same(email) The same as another field
different(username) Different from another field
alpha Letters only, from any language, such as José
alpha_num Letters from any language, and numbers
alpha_dash Letters from any language, numbers, dashes, and underscores
ascii ASCII characters only. Add it to alpha_dash for a username such as jane_doe
lowercase Already lowercase
uppercase Already uppercase
starts_with("+1", "+44") Starts with one of the prefixes
ends_with(".jpg", ".png") Ends with one of the suffixes
doesnt_start_with("_") Starts with none of the prefixes
doesnt_end_with(".exe") Ends with none of the suffixes
digits(4) Exactly 4 digits
digits_between(4, 6) Between 4 and 6 digits
min_digits(4) At least 4 digits
max_digits(6) At most 6 digits

Lengths count characters, not bytes, and limits are inclusive.

Numbers

Attribute Passes when the value is
min_value(1) At least 1
max_value(100) At most 100
between(0.0, 5.0) From 0 to 5, inclusive
gt(minimum) Greater than another field
gte(minimum) Greater than or equal to another field
lt(price) Less than another field
lte(price) Less than or equal to another field
decimal(2) A number with exactly 2 decimal places
decimal(2, 4) A number with 2 to 4 decimal places
multiple_of(12) A multiple of 12

These rules compare numbers, not text lengths, and they accept numbers sent as text, such as a form's "12.50". For example, this form accepts an order of 1 to 100 items, and an optional rating from 0 to 5:

1#[laravel::input]
2pub struct StoreOrder {
3 #[validate(required, min_value(1), max_value(100))]
4 quantity: u32,
5 #[validate(between(0.0, 5.0))]
6 rating: Option<f64>,
7}
1#[laravel::input]
2pub struct StoreOrder {
3 #[validate(required, min_value(1), max_value(100))]
4 quantity: u32,
5 #[validate(between(0.0, 5.0))]
6 rating: Option<f64>,
7}

gt, gte, lt, and lte always name another field, never a literal number. Use min_value, max_value, or between for a fixed limit. A comparison fails when the other field is missing, so add required to that field if clients must send it:

1#[laravel::input]
2pub struct PriceRange {
3 #[validate(required, min_value(0), label = "minimum price")]
4 minimum: u64,
5 #[validate(required, gte(minimum), label = "maximum price")]
6 maximum: u64,
7}
1#[laravel::input]
2pub struct PriceRange {
3 #[validate(required, min_value(0), label = "minimum price")]
4 minimum: u64,
5 #[validate(required, gte(minimum), label = "maximum price")]
6 maximum: u64,
7}

Decimal places and multiples

decimal counts the decimal places the user wrote. With decimal(2), "12.50" passes, while "12", "12.5", and "12.500" fail. Add min_value(0) if a price can't be negative:

1use laravel::numeric::Decimal;
2 
3#[laravel::input]
4pub struct StoreProduct {
5 #[validate(required, decimal(2), min_value(0))]
6 price: Decimal,
7 #[validate(required, multiple_of(12))]
8 quantity: u32,
9}
1use laravel::numeric::Decimal;
2 
3#[laravel::input]
4pub struct StoreProduct {
5 #[validate(required, decimal(2), min_value(0))]
6 price: Decimal,
7 #[validate(required, multiple_of(12))]
8 quantity: u32,
9}

For money and other exact amounts, use laravel::numeric::Decimal rather than f64. Valid<T> decodes form text and JSON numbers into a Decimal without rounding them, and databases store it exactly. An f64 field receives an approximate value.

Dates and times

Attribute Passes when the value is
date A real calendar date, such as 2024-02-29
datetime A timestamp with a UTC offset, such as 2024-02-29T09:30:00Z
date_format("%d/%m/%Y") Text in one of the formats
timezone A time zone name, such as America/Chicago
after(starts_on) After another field's date or time
after_or_equal(starts_on) On or after another field's date or time
before(ends_on) Before another field's date or time
before_or_equal(ends_on) On or before another field's date or time
date_equals(starts_on) The same as another field's date or time
after_today A date after today
today_or_after Today or a later date
before_today A date before today
today_or_before Today or an earlier date

An HTML <input type="date"> submits a date such as 2024-02-29. Declare the field as a laravel::time::civil::Date, and Laravel checks that the value is a real calendar date, as the date rule does. Your handler then receives a typed date:

1use laravel::time::civil::Date;
2 
3#[laravel::input]
4pub struct StoreBooking {
5 #[validate(required, today_or_after, label = "arrival date")]
6 starts_on: Date,
7 #[validate(required, after_or_equal(starts_on), label = "departure date")]
8 ends_on: Date,
9}
1use laravel::time::civil::Date;
2 
3#[laravel::input]
4pub struct StoreBooking {
5 #[validate(required, today_or_after, label = "arrival date")]
6 starts_on: Date,
7 #[validate(required, after_or_equal(starts_on), label = "departure date")]
8 ends_on: Date,
9}

In this example, a guest may book a stay that starts today or later, and ends on or after the day it starts. Laravel compares dates with today's date in UTC, the time zone its clock uses, so today may already be tomorrow for a user in another part of the world.

timezone accepts a name from the IANA time zone database, such as America/Chicago or UTC. Declare the field as a String, and pass it to in_tz when you'd like to show a time in the user's time zone. For example, laravel::now().in_tz(&form.timezone)? returns the current time in that zone, as a ZonedDateTime. To learn more, check out the dates and time guide's section on timezones.

Date-times

datetime requires an RFC 3339 timestamp with seconds and a UTC offset, such as 2024-02-29T09:30:00Z or 2024-02-29T09:30:00-05:00. A laravel::time::Timestamp field checks this format on its own, as the datetime rule does, and your handler receives the moment in time the value describes. When a rule such as after compares two timestamps, it compares the moments they describe, not the clock times as written. For example, 2024-02-29T09:30:00-05:00 is after 2024-02-29T10:00:00Z, because 9:30 in New York is 14:30 in UTC:

1use laravel::time::Timestamp;
2 
3#[laravel::input]
4pub struct StoreAppointment {
5 #[validate(required, label = "start time")]
6 starts_at: Timestamp,
7 #[validate(required, after(starts_at), label = "end time")]
8 ends_at: Timestamp,
9}
1use laravel::time::Timestamp;
2 
3#[laravel::input]
4pub struct StoreAppointment {
5 #[validate(required, label = "start time")]
6 starts_at: Timestamp,
7 #[validate(required, after(starts_at), label = "end time")]
8 ends_at: Timestamp,
9}

An HTML <input type="datetime-local"> submits a time without an offset, so it can't pass datetime. Validate it with date_format("%Y-%m-%dT%H:%M"), and choose the time zone in your handler.

Date formats

The date and datetime rules accept only the standard formats that a browser's date inputs and most APIs send, such as 2024-02-29. Sometimes dates arrive in another format, such as a birthday that users type as 29/02/2024 into a plain text input. For those fields, use date_format instead, with the format you expect, written as a strftime format such as %d/%m/%Y. The text must be a real date in exactly that format, so %d/%m/%Y rejects both 29/02/2023 and 1/02/2024.

Since the text isn't in a standard format, declare the field as a String, and parse it into a date after validation:

1use laravel::time::civil::Date;
2use laravel::validation::Valid;
3 
4#[laravel::input]
5#[validate(authenticated)]
6pub struct UpdateProfile {
7 #[validate(required, date_format("%d/%m/%Y"))]
8 birthday: String,
9}
10 
11pub async fn update(Valid(form): Valid<UpdateProfile>) -> laravel::Result<Redirect> {
12 let birthday = Date::strptime("%d/%m/%Y", &form.birthday)?;
13 
14 // Store the birthday...
15 
16 Ok(Redirect::back())
17}
1use laravel::time::civil::Date;
2use laravel::validation::Valid;
3 
4#[laravel::input]
5#[validate(authenticated)]
6pub struct UpdateProfile {
7 #[validate(required, date_format("%d/%m/%Y"))]
8 birthday: String,
9}
10 
11pub async fn update(Valid(form): Valid<UpdateProfile>) -> laravel::Result<Redirect> {
12 let birthday = Date::strptime("%d/%m/%Y", &form.birthday)?;
13 
14 // Store the birthday...
15 
16 Ok(Redirect::back())
17}

The date comparison rules, such as after and today_or_after, only understand the standard formats. So to compare a date that arrives in another format, parse it in your handler and compare it there.

Formats

Attribute Passes when the value is
email An email address
url An http or https URL
url("https", "wss") A URL with one of the schemes
uuid A UUID in its hyphenated form
uuid(7) A UUID of version 7
ulid A ULID
ip An IPv4 or IPv6 address
ipv4 An IPv4 address
ipv6 An IPv6 address
mac_address A MAC address
hex_color A color such as #1e90ff
json JSON text
base64 Padded Base64 text
regex(r"\A[A-Z]{3}\z") Text that matches the pattern
not_regex(r"(?i)admin") Text that doesn't match the pattern

For example, this form checks a contact's email address, an optional website, and a callback URL that must use HTTPS:

1#[laravel::input]
2pub struct UpdateContact {
3 #[validate(required, email)]
4 email: String,
5 #[validate(url)]
6 website: Option<String>,
7 #[validate(url("https").message("Please enter an HTTPS callback URL."))]
8 callback: Option<String>,
9}
1#[laravel::input]
2pub struct UpdateContact {
3 #[validate(required, email)]
4 email: String,
5 #[validate(url)]
6 website: Option<String>,
7 #[validate(url("https").message("Please enter an HTTPS callback URL."))]
8 callback: Option<String>,
9}

Most of the time, you don't need the ip, uuid, or ulid rules. Declare the field with the type it holds instead, such as std::net::IpAddr, Ipv4Addr, or Ipv6Addr for an IP address, or laravel::str::Uuid or laravel::str::Ulid for an ID. Laravel checks the value's format as the matching rule would, and shows the rule's error message when the format is wrong. Your handler then receives the parsed value:

1use std::net::IpAddr;
2 
3use laravel::str::Uuid;
4 
5#[laravel::input]
6pub struct StoreDevice {
7 device_id: Uuid,
8 address: IpAddr,
9}
1use std::net::IpAddr;
2 
3use laravel::str::Uuid;
4 
5#[laravel::input]
6pub struct StoreDevice {
7 device_id: Uuid,
8 address: IpAddr,
9}

Use the rules on String fields, or to require a UUID version, as in uuid(7).

Regular expressions

Patterns use Rust regex syntax, without / delimiters. A pattern matches anywhere in the text, so anchor it with \A and \z to match the whole value:

1#[laravel::input]
2pub struct StoreProduct {
3 #[validate(required, regex(r"\A[A-Z]{3}-[0-9]{4}\z"))]
4 sku: String,
5}
1#[laravel::input]
2pub struct StoreProduct {
3 #[validate(required, regex(r"\A[A-Z]{3}-[0-9]{4}\z"))]
4 sku: String,
5}

Rust's regex syntax doesn't support look-around or backreferences.

Presence and acceptance

Attribute Passes when the field is
required Present and not empty. 0 and false pass
filled Not empty, if it's present
present Present, even if empty
missing Absent. Even a null fails
prohibited Absent or empty
accepted "yes", "on", "1", 1, true, or "true"
declined "no", "off", "0", 0, false, or "false"

An empty value is null, blank text, or an empty list. Unlike other rules, these rules check fields that are missing or empty. When one of them fails, Laravel skips the field's later rules. The one rule that doesn't do this is prohibited. If a field the user shouldn't have sent is also malformed, the user sees both errors. To learn more about rules that only apply when another field has a certain value, such as required_if, check out conditional rules.

Use accepted for a checkbox that the user must tick, such as accepting your terms of service. A browser doesn't submit an unchecked checkbox at all, so give an optional checkbox's bool field #[serde(default)]. Without it, an unchecked box fails with "The newsletter field is required.":

1use laravel::hash::Password;
2 
3#[laravel::input]
4pub struct Register {
5 #[validate(required, email)]
6 email: String,
7 #[validate(required, password, confirmed)]
8 password: Password,
9 #[validate(accepted)]
10 terms: bool,
11 #[serde(default)]
12 newsletter: bool,
13}
1use laravel::hash::Password;
2 
3#[laravel::input]
4pub struct Register {
5 #[validate(required, email)]
6 email: String,
7 #[validate(required, password, confirmed)]
8 password: Password,
9 #[validate(accepted)]
10 terms: bool,
11 #[serde(default)]
12 newsletter: bool,
13}

Database records

unique checks that no row of a table already has the submitted value, such as an email address that's already taken. exists checks that some row of a table has the submitted value, such as the ID of a category the user picked. Pass each rule the column of the model to check:

1use crate::models::{Category, Post, Tag};
2 
3#[laravel::input]
4pub struct StorePost {
5 #[validate(required, max_length(255), unique(Post::slug))]
6 slug: String,
7 #[validate(required, exists(Category::id))]
8 category_id: i64,
9 #[validate(bail, max_items(20), each(exists(Tag::id)))]
10 tag_ids: Vec<i64>,
11}
1use crate::models::{Category, Post, Tag};
2 
3#[laravel::input]
4pub struct StorePost {
5 #[validate(required, max_length(255), unique(Post::slug))]
6 slug: String,
7 #[validate(required, exists(Category::id))]
8 category_id: i64,
9 #[validate(bail, max_items(20), each(exists(Tag::id)))]
10 tag_ids: Vec<i64>,
11}

The rules query the model's table on the model's database connection. The field's type must match the column's type, so a String field with exists(Category::id) doesn't compile.

For a table without a model, pass the table's name and then the column's name, as in exists("categories", "id"). Without a column name, the rule uses the field's Rust name, so unique("posts") on slug checks posts.slug. A table name always queries the default connection.

Each rule checks one value. To check each ID in a list, use each(exists(..)). That runs one query per item, so limit the list with max_items and add bail, which stops a list that's too long before any queries run.

The comparison follows the column's collation. A MySQL column with a case-insensitive collation finds [email protected] when the row has [email protected], while PostgreSQL and SQLite compare text exactly. For fields like email addresses, add #[transform(lowercase)] to normalize the value before validation and storage, as Transforming input fields describes.

Ignoring a row

When users update their profile, their current email address is already in the users table, so a plain unique rule reports it as taken. Add ignore = user to skip the logged-in user's row:

1#[laravel::input]
2pub struct UpdateProfile {
3 #[validate(required, email, unique(User::email, ignore = user))]
4 email: String,
5}
1#[laravel::input]
2pub struct UpdateProfile {
3 #[validate(required, email, unique(User::email, ignore = user))]
4 email: String,
5}

A page that edits another record has the same problem. On PUT /teams/{team}, the team's own row already holds its current name. Add ignore = route("team") to skip the team that the URL names:

1use laravel::model::update;
2use laravel::prelude::*;
3 
4use crate::models::Team;
5 
6#[laravel::input(fills = Team)]
7#[validate(authenticated)]
8pub struct UpdateTeam {
9 #[validate(required, unique(Team::name, ignore = route("team")))]
10 name: String,
11}
12 
13// PUT /teams/{team}
14pub async fn update(
15 mut team: Team,
16 Valid(input): Valid<UpdateTeam>,
17) -> laravel::Result<Redirect> {
18 update!(team { ..input }).await?;
19 
20 Ok(Redirect::back())
21}
1use laravel::model::update;
2use laravel::prelude::*;
3 
4use crate::models::Team;
5 
6#[laravel::input(fills = Team)]
7#[validate(authenticated)]
8pub struct UpdateTeam {
9 #[validate(required, unique(Team::name, ignore = route("team")))]
10 name: String,
11}
12 
13// PUT /teams/{team}
14pub async fn update(
15 mut team: Team,
16 Valid(input): Valid<UpdateTeam>,
17) -> laravel::Result<Redirect> {
18 update!(team { ..input }).await?;
19 
20 Ok(Redirect::back())
21}

The rule finds the team as a team: Team handler argument would, so it also works for a team route that uses a slug.

ignore = user reads the user from the session, so it needs a route with a session or a request guard. When the ID comes from somewhere else, add the rule with Rule::unique(..).ignore(id) in a rules function, or check the record in your handler and return an error with invalid!.

Filtering rows

Sometimes only some rows should count, such as categories that haven't been archived. filter limits a unique or exists rule to the rows that meet a query builder condition. For example, this rule only accepts categories that aren't archived:

1use crate::models::Category;
2 
3#[laravel::input]
4pub struct StorePost {
5 #[validate(required, exists(Category::id, filter = Category::archived_at.is_null()))]
6 category_id: i64,
7}
1use crate::models::Category;
2 
3#[laravel::input]
4pub struct StorePost {
5 #[validate(required, exists(Category::id, filter = Category::archived_at.is_null()))]
6 category_id: i64,
7}

Combine conditions with &, |, and !, as in filter = Category::active.eq(true) & !Category::hidden.eq(true). With a table name, write the condition with laravel::db::col, as in exists("categories", "id", filter = col("archived_at").is_null()).

On a route that uses route model binding, such as POST /projects/{project}/issues, a filter often needs the bound model. Here, an issue's labels must belong to the project in the URL. To compare a column with that project's key, write route::<Project>("project") in the condition. The rule finds the project that {project} names and compares the column with its key:

1use laravel::prelude::*;
2 
3use crate::models::{Label, Project};
4 
5#[laravel::input]
6#[validate(authenticated)]
7pub struct StoreIssue {
8 #[validate(required, max_length(255))]
9 title: String,
10 #[serde(default)]
11 #[validate(
12 max_items(10),
13 each(exists(Label::id, filter = Label::project_id.eq(route::<Project>("project")))),
14 )]
15 label_ids: Vec<i64>,
16}
17 
18// POST /projects/{project}/issues
19pub async fn store(
20 project: Project,
21 Valid(input): Valid<StoreIssue>,
22) -> laravel::Result<Redirect> {
23 // Create the issue...
24 
25 Ok(Redirect::back())
26}
1use laravel::prelude::*;
2 
3use crate::models::{Label, Project};
4 
5#[laravel::input]
6#[validate(authenticated)]
7pub struct StoreIssue {
8 #[validate(required, max_length(255))]
9 title: String,
10 #[serde(default)]
11 #[validate(
12 max_items(10),
13 each(exists(Label::id, filter = Label::project_id.eq(route::<Project>("project")))),
14 )]
15 label_ids: Vec<i64>,
16}
17 
18// POST /projects/{project}/issues
19pub async fn store(
20 project: Project,
21 Valid(input): Valid<StoreIssue>,
22) -> laravel::Result<Redirect> {
23 // Create the issue...
24 
25 Ok(Redirect::back())
26}

A label from another project fails with "The selected label_ids.0 is invalid."

When a condition needs a route parameter that isn't a model, add the rule in your rules function. For example, if an invitation's email address must be unique within the team named in the route, read the route parameter and filter Rule::unique with it:

1use laravel::prelude::*;
2use laravel::validation::{Rule, Rules, ValidatesRequest};
3 
4use crate::models::Member;
5 
6#[laravel::input]
7pub struct StoreInvitation {
8 #[validate(required, email)]
9 email: String,
10}
11 
12impl ValidatesRequest for StoreInvitation {
13 async fn authorize(request: &Request) -> laravel::Result<bool> {
14 Ok(request.authenticated().await?)
15 }
16 
17 async fn rules(&self, request: &Request, rules: Rules) -> laravel::Result<Rules> {
18 let team: i64 = request
19 .route("team")
20 .and_then(|id| id.parse().ok())
21 .or_abort(404)?;
22 
23 Ok(rules.field(
24 "email",
25 [Rule::unique(Member::email).filter(Member::team_id.eq(team))],
26 ))
27 }
28}
1use laravel::prelude::*;
2use laravel::validation::{Rule, Rules, ValidatesRequest};
3 
4use crate::models::Member;
5 
6#[laravel::input]
7pub struct StoreInvitation {
8 #[validate(required, email)]
9 email: String,
10}
11 
12impl ValidatesRequest for StoreInvitation {
13 async fn authorize(request: &Request) -> laravel::Result<bool> {
14 Ok(request.authenticated().await?)
15 }
16 
17 async fn rules(&self, request: &Request, rules: Rules) -> laravel::Result<Rules> {
18 let team: i64 = request
19 .route("team")
20 .and_then(|id| id.parse().ok())
21 .or_abort(404)?;
22 
23 Ok(rules.field(
24 "email",
25 [Rule::unique(Member::email).filter(Member::team_id.eq(team))],
26 ))
27 }
28}

Rule::unique and Rule::exists return builders so you may chain options such as ignore and filter. Because a builder has a different type from other rules, combine it with other rules in a tuple rather than an array:

1rules.field(
2 "email",
3 (
4 Rule::max_length(255),
5 Rule::unique(Member::email).filter(Member::team_id.eq(team)),
6 ),
7)
1rules.field(
2 "email",
3 (
4 Rule::max_length(255),
5 Rule::unique(Member::email).filter(Member::team_id.eq(team)),
6 ),
7)

Passwords

When users choose a new password, such as on your registration and password reset forms, you'll usually want every form to enforce the same complexity requirements. The password rule validates a field against your application's default password rules:

1use laravel::hash::Password;
2 
3#[laravel::input]
4pub struct ResetPassword {
5 #[validate(required, email)]
6 email: String,
7 #[validate(required, password, confirmed)]
8 password: Password,
9}
1use laravel::hash::Password;
2 
3#[laravel::input]
4pub struct ResetPassword {
5 #[validate(required, email)]
6 email: String,
7 #[validate(required, password, confirmed)]
8 password: Password,
9}

By default, the password rule requires at least 8 characters. To customize your application's password requirements in one place, register a PasswordRule inside with_services in src/app.rs:

1use laravel::validation::PasswordRule;
2 
3Application::configure()
4 .with_services(|app| {
5 app.instance(PasswordRule::min(8).letters().mixed_case().numbers());
6 })
1use laravel::validation::PasswordRule;
2 
3Application::configure()
4 .with_services(|app| {
5 app.instance(PasswordRule::min(8).letters().mixed_case().numbers());
6 })
Method Requires
PasswordRule::min(8) At least 8 characters
max(64) At most 64 characters
letters() At least one letter
mixed_case() At least one uppercase and one lowercase letter
numbers() At least one number
symbols() At least one symbol, such as punctuation or a space

If a specific form needs different requirements than your application defaults, such as an admin password requiring 12 characters and a symbol, pass those options directly to the password rule:

1#[validate(required, password(min = 12, symbols), confirmed)]
2password: Password,
1#[validate(required, password(min = 12, symbols), confirmed)]
2password: Password,

Current password

current_password checks that the field matches the logged-in user's password. Use it on forms that change a user's password or email address:

1use laravel::hash::Password;
2 
3#[laravel::input]
4pub struct UpdatePassword {
5 #[validate(required, current_password)]
6 current_password: Password,
7 #[validate(required, password, confirmed)]
8 password: Password,
9}
1use laravel::hash::Password;
2 
3#[laravel::input]
4pub struct UpdatePassword {
5 #[validate(required, current_password)]
6 current_password: Password,
7 #[validate(required, password, confirmed)]
8 password: Password,
9}

The rule fails with "The password is incorrect." for a wrong password and for a guest. Like ignore = user, it reads the user from the session or a request guard.

Declare password fields as laravel::hash::Password rather than String, as this form does. A Password keeps the plain-text password out of your logs, and Laravel never flashes it to the session as old input. To learn more, check out the hashing guide's section on password fields.

Files

To validate an uploaded file, declare it as an UploadedFile field and put the file's rules on the field. Your handler then receives the file in the validated struct, so it may store the file:

1use laravel::http::UploadedFile;
2use laravel::prelude::*;
3 
4#[laravel::input]
5#[validate(authenticated)]
6pub struct UpdateProfile {
7 #[validate(required, max_length(255))]
8 name: String,
9 #[validate(required, image, max_kilobytes(2048))]
10 avatar: UploadedFile,
11 #[validate(mimes("pdf"), max_kilobytes(10240))]
12 resume: Option<UploadedFile>,
13}
14 
15pub async fn update(Valid(form): Valid<UpdateProfile>) -> laravel::Result<Redirect> {
16 let path = form.avatar.store("avatars").disk("public").await?;
17 
18 // Save the avatar's path...
19 
20 Ok(Redirect::back())
21}
1use laravel::http::UploadedFile;
2use laravel::prelude::*;
3 
4#[laravel::input]
5#[validate(authenticated)]
6pub struct UpdateProfile {
7 #[validate(required, max_length(255))]
8 name: String,
9 #[validate(required, image, max_kilobytes(2048))]
10 avatar: UploadedFile,
11 #[validate(mimes("pdf"), max_kilobytes(10240))]
12 resume: Option<UploadedFile>,
13}
14 
15pub async fn update(Valid(form): Valid<UpdateProfile>) -> laravel::Result<Redirect> {
16 let path = form.avatar.store("avatars").disk("public").await?;
17 
18 // Save the avatar's path...
19 
20 Ok(Redirect::back())
21}

Use Option<UploadedFile> for an optional file. For an <input type="file" multiple> named photos[], use Vec<UploadedFile>, and the rules check every file. min_items and max_items limit how many files the list holds.

Attribute Passes when the field is
file An uploaded file
image A JPEG, PNG, GIF, BMP, or WebP image
mimes("pdf", "video/*") A file of one of these types, named by extension, such as pdf, or by MIME type, such as video/* for any video
extensions("csv") A file whose name has one of these extensions
min_kilobytes(10) A file of at least 10 kilobytes
max_kilobytes(2048) A file of at most 2,048 kilobytes

image and mimes check the file's contents, not the name the user gave it, so a renamed text file fails image. SVG fails image, because an SVG can carry scripts.

A text format such as CSV has nothing in its contents that identifies it, so mimes("csv") rejects every CSV file. Check those files with extensions instead. It only looks at the end of the file's name, such as .csv, so it can't tell whether a file named contacts.csv really is a CSV.

The LimitUploads middleware rejects a form that's too large before validation reads it, so set its limit above your largest max_kilobytes.

Conditional rules

Some fields matter only when another field has a certain value. A shipping address is required when the customer wants delivery, and pickup instructions make no sense then. Declare such fields as Option, so they may be absent when their condition doesn't apply:

1#[laravel::input]
2pub struct StoreShipment {
3 #[validate(required, one_of("ship", "pickup"))]
4 delivery: String,
5 #[validate(required_if(delivery, "ship"))]
6 address: Option<String>,
7 #[validate(prohibited_if(delivery, "ship"))]
8 pickup_notes: Option<String>,
9}
1#[laravel::input]
2pub struct StoreShipment {
3 #[validate(required, one_of("ship", "pickup"))]
4 delivery: String,
5 #[validate(required_if(delivery, "ship"))]
6 address: Option<String>,
7 #[validate(prohibited_if(delivery, "ship"))]
8 pickup_notes: Option<String>,
9}
Attribute The field is required, or must be empty
required_if(delivery, "ship") Required when delivery is ship
required_unless(delivery, "pickup") Required unless delivery is pickup
required_with(phone, email) Required when any of the fields isn't empty
required_with_all(phone, email) Required when none of the fields is empty
required_without(phone, email) Required when any of the fields is empty
required_without_all(phone, email) Required when all of the fields are empty
required_if_accepted(terms) Required when the field is accepted
required_if_declined(terms) Required when the field is declined
prohibited_if(delivery, "pickup") Empty when delivery is pickup
prohibited_unless(delivery, "ship") Empty unless delivery is ship
prohibited_if_accepted(terms) Empty when the field is accepted
prohibited_if_declined(terms) Empty when the field is declined
prohibits(phone, email) The other fields must be empty when this one isn't
accepted_if(delivery, "ship") Accepted when delivery is ship
declined_if(delivery, "ship") Declined when delivery is ship

To check whether a field was submitted regardless of its value, use present_if, present_unless, present_with, present_with_all, missing_if, missing_unless, missing_with, or missing_with_all.

The field a conditional rule names belongs to the same struct as the rule. So when a form sends a list of addresses, each address checks its own country. In this example, an address in the US must have a state, while an address in Canada doesn't need one:

1#[laravel::input]
2pub struct StoreShipments {
3 #[validate(required)]
4 addresses: Vec<Address>,
5}
6 
7#[laravel::input]
8pub struct Address {
9 #[validate(required)]
10 country: String,
11 #[validate(required_if(country, "US"))]
12 state: Option<String>,
13}
1#[laravel::input]
2pub struct StoreShipments {
3 #[validate(required)]
4 addresses: Vec<Address>,
5}
6 
7#[laravel::input]
8pub struct Address {
9 #[validate(required)]
10 country: String,
11 #[validate(required_if(country, "US"))]
12 state: Option<String>,
13}

To check a field inside a nested struct, reference it through the struct's field path. For example, this order requires a phone number when its shipping address is in the US:

1#[laravel::input]
2pub struct StoreOrder {
3 shipping: Address,
4 #[validate(required_if(shipping.country, "US"))]
5 phone: Option<String>,
6}
1#[laravel::input]
2pub struct StoreOrder {
3 shipping: Address,
4 #[validate(required_if(shipping.country, "US"))]
5 phone: Option<String>,
6}

A conditional rule references the other field by its Rust name, even when the request sends it under another name. For example, a JavaScript client might send shippingCountry and phoneNumber, which #[serde(rename_all = "camelCase")] maps to the struct's shipping_country and phone_number fields. The rule still writes shipping_country, and every segment of a field path is checked at compile time, so a misspelled field won't compile:

1#[laravel::input]
2#[serde(rename_all = "camelCase")]
3pub struct StoreOrder {
4 shipping_country: String,
5 #[validate(required_if(shipping_country, "US"))]
6 phone_number: Option<String>,
7}
1#[laravel::input]
2#[serde(rename_all = "camelCase")]
3pub struct StoreOrder {
4 shipping_country: String,
5 #[validate(required_if(shipping_country, "US"))]
6 phone_number: Option<String>,
7}

Rules you add in code, such as in a rules function, work on the request's input directly, so they name fields as the request sends them, such as "phoneNumber".

The value a rule compares with must match exactly, so required_if(country, "US") doesn't apply when the request sends "us".

Booleans and numbers are more forgiving. HTML forms send every value as text, so a checked checkbox arrives as "on" rather than true. Laravel accounts for this, so required_if(enabled, true) applies whether a JSON client sends true or a form sends "on". In the same way, required_if(count, 2) matches both 2 and "2".

Nested objects

Sometimes a request nests related fields inside an object, such as the shipping and billing addresses of a checkout. A JSON client sends each address as an object, as in {"shipping": {"city": "Chicago"}}, and an HTML form names the address's fields with brackets, as in <input name="shipping[city]">. Laravel reads both into the same shape.

To validate a nested object, declare it as its own struct marked #[laravel::input], such as an Address struct. A field of that type, such as shipping: Address, then checks the nested object with the Address struct's rules:

1#[laravel::input]
2pub struct StoreOrder {
3 shipping: Address,
4 billing: Option<Address>,
5}
6 
7#[laravel::input]
8pub struct Address {
9 #[validate(required, max_length(255))]
10 street: String,
11 #[validate(required)]
12 city: String,
13 country: String,
14 #[validate(required_if(country, "US"))]
15 postal_code: Option<String>,
16}
1#[laravel::input]
2pub struct StoreOrder {
3 shipping: Address,
4 billing: Option<Address>,
5}
6 
7#[laravel::input]
8pub struct Address {
9 #[validate(required, max_length(255))]
10 street: String,
11 #[validate(required)]
12 city: String,
13 country: String,
14 #[validate(required_if(country, "US"))]
15 postal_code: Option<String>,
16}

If the shipping address is missing its city, Laravel reports the error under shipping.city, so your form can show it next to the right input. The billing field is an Option, so a customer may leave out the billing address, such as to be billed at the shipping address. When the request does include a billing address, Laravel checks it with the same Address rules.

Only StoreOrder needs to say who may submit the form, such as with #[validate(anyone)]. The Address struct doesn't, because Laravel only checks it as part of an order.

When you accept a nested object as a map instead of a struct, you may restrict its keys with allowed_keys and required_keys. For example, you might allow a contact's name and email while rejecting any other keys, and require that the email key is always present (even if its value is null):

1use std::collections::HashMap;
2 
3#[laravel::input]
4#[validate(anyone)]
5pub struct UpdateContact {
6 #[validate(allowed_keys("name", "email"), required_keys("email"))]
7 contact: HashMap<String, Option<String>>,
8}
1use std::collections::HashMap;
2 
3#[laravel::input]
4#[validate(anyone)]
5pub struct UpdateContact {
6 #[validate(allowed_keys("name", "email"), required_keys("email"))]
7 contact: HashMap<String, Option<String>>,
8}

Map values support the same per-entry validation as lists. A HashMap or BTreeMap whose values are a #[laravel::input] struct validates every entry with that struct's rules, and each(...) applies rules to each value in a map of strings, numbers, or files. For example, a form that submits a translated title per language (titles[en], titles[fr]) might cap every title's length:

1use std::collections::HashMap;
2 
3#[laravel::input]
4#[validate(anyone)]
5pub struct StorePost {
6 #[validate(required, each(required, max_length(255)))]
7 titles: HashMap<String, String>,
8}
1use std::collections::HashMap;
2 
3#[laravel::input]
4#[validate(anyone)]
5pub struct StorePost {
6 #[validate(required, each(required, max_length(255)))]
7 titles: HashMap<String, String>,
8}

Laravel reports a value's errors under its key, such as titles.fr.

Validating lists

Many forms send lists, such as the items in an order or the tags on a post. A Vec field of a struct marked #[laravel::input] validates every item with that struct's rules. For a list of text or numbers, put the rules for each item in each(...):

1use crate::models::Product;
2 
3#[laravel::input]
4pub struct StoreOrder {
5 #[validate(required, max_items(50))]
6 items: Vec<OrderItem>,
7 #[validate(max_items(10), distinct, each(required, max_length(50)))]
8 tags: Vec<String>,
9}
10 
11#[laravel::input]
12pub struct OrderItem {
13 #[validate(required, exists(Product::id))]
14 product_id: i64,
15 #[validate(required, min_value(1))]
16 quantity: u32,
17}
1use crate::models::Product;
2 
3#[laravel::input]
4pub struct StoreOrder {
5 #[validate(required, max_items(50))]
6 items: Vec<OrderItem>,
7 #[validate(max_items(10), distinct, each(required, max_length(50)))]
8 tags: Vec<String>,
9}
10 
11#[laravel::input]
12pub struct OrderItem {
13 #[validate(required, exists(Product::id))]
14 product_id: i64,
15 #[validate(required, min_value(1))]
16 quantity: u32,
17}

Rules outside each(...) apply to the list itself, so required rejects an empty list. Laravel reports an item's errors in "dot" notation, with the item's position in the list, such as items.2.quantity for the quantity of the third item, or tags.3 for the fourth tag. Forms submit lists with brackets, as in tags[]=rust or items[0][quantity]=2, and JSON clients send arrays.

Attribute Passes when the list
min_items(1) Has at least 1 item
max_items(10) Has at most 10 items
distinct Has no duplicate items
contains("editor") Includes every one of the listed values
doesnt_contain("admin") Includes none of the listed values
list Has keys 0, 1, 2, and so on, in order

Option<Vec<T>> accepts a missing list, and Vec<Option<T>> accepts null items.

Contains and distinct

contains, doesnt_contain, and distinct compare text case-sensitively and untyped JSON values strictly. On numeric or boolean collections such as Vec<u64> or Vec<bool>, they compare the decoded numeric or boolean values so "1" and 1 match:

1#[laravel::input]
2pub struct UpdateRoles {
3 #[validate(required, contains("member"), doesnt_contain("owner"), distinct)]
4 roles: Vec<String>,
5}
1#[laravel::input]
2pub struct UpdateRoles {
3 #[validate(required, contains("member"), doesnt_contain("owner"), distinct)]
4 roles: Vec<String>,
5}

Custom messages and labels

Every built-in rule has an English message with the field's name filled in, such as "The email field is required." To show a different name in the messages, such as "email address" instead of "email", set the field's label. To replace a rule's message, chain .message(...) directly onto the rule:

1#[laravel::input]
2pub struct StoreUser {
3 #[validate(
4 required.message("Please enter your :attribute."),
5 email,
6 label = "email address",
7 )]
8 email: String,
9}
1#[laravel::input]
2pub struct StoreUser {
3 #[validate(
4 required.message("Please enter your :attribute."),
5 email,
6 label = "email address",
7 )]
8 email: String,
9}

A missing email now reads "Please enter your email address.", and an invalid one reads "The email address field must be a valid email address." Labels change only the message, not the field's key in errors.

When a rule's message mentions another field, it uses that field's label too. For example, if starts_on has the label "arrival date", and ends_on has the label "departure date", the after(starts_on) rule on ends_on fails with "The departure date field must be a date after arrival date."

For a list, put rules that check the whole list, such as distinct, on the field. Put rules that check one item inside each(...). You may give either kind of rule a custom message, and you may chain .label(...) onto each(...) to name the items:

1#[laravel::input]
2pub struct StoreArticle {
3 #[validate(
4 max_items(10).message("Choose at most :max tags."),
5 distinct.message("Choose a different name for each tag."),
6 each(
7 required.message("Tag #:position can't be blank."),
8 max_length(50).message(":Attribute #:position must be at most :max characters."),
9 )
10 .label("tag"),
11 )]
12 tags: Vec<String>,
13}
1#[laravel::input]
2pub struct StoreArticle {
3 #[validate(
4 max_items(10).message("Choose at most :max tags."),
5 distinct.message("Choose a different name for each tag."),
6 each(
7 required.message("Tag #:position can't be blank."),
8 max_length(50).message(":Attribute #:position must be at most :max characters."),
9 )
10 .label("tag"),
11 )]
12 tags: Vec<String>,
13}

Messages may use these placeholders:

Placeholder Value
:attribute The field's label. Without one, its name in words, so last_name reads "last name"
:Attribute, :ATTRIBUTE The label with its first letter capitalized, or in capitals
:min, :max, :digits The rule's limits or digit count
:other, :date The label of the field that a rule compares with
:value, :values The value or values that a rule compares with
:format The formats of date_format
:index, :position The list item's index, from 0, or its position, from 1

A field's type checks its value too, even without a rule. For example, a u32 field rejects "two", and a Uuid field rejects text that isn't a UUID. To replace the message for that check, set invalid on the field (or chain .invalid(...) onto each(...) for list items):

1use laravel::str::Uuid;
2 
3#[laravel::input]
4pub struct StoreTickets {
5 #[validate(invalid = "Enter a whole number of tickets.")]
6 quantity: u32,
7 #[validate(invalid = "That event ID isn't valid.")]
8 event_id: Uuid,
9}
1use laravel::str::Uuid;
2 
3#[laravel::input]
4pub struct StoreTickets {
5 #[validate(invalid = "Enter a whole number of tickets.")]
6 quantity: u32,
7 #[validate(invalid = "That event ID isn't valid.")]
8 event_id: Uuid,
9}

The invalid message only replaces the message for a value that doesn't fit the field's type. Failures of the rules you declare, such as required or max_length, keep their own messages.

Custom rules

When the built-in rules don't cover a check, write your own. Implement ValidationRule and use the rule in #[validate(...)]. You don't register it anywhere:

1use laravel::validation::{Field, RuleError, ValidationRule};
2 
3pub struct Slug;
4 
5impl ValidationRule for Slug {
6 async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError> {
7 match field.value.and_then(|value| value.as_str()) {
8 Some(value) if value.chars().all(|c| c.is_ascii_lowercase() || c == '-') => Ok(()),
9 _ => Err(field.reject("The :attribute field must be a slug.")),
10 }
11 }
12}
13 
14#[laravel::input]
15pub struct StoreArticle {
16 #[validate(required, max_length(100), Slug)]
17 slug: String,
18}
1use laravel::validation::{Field, RuleError, ValidationRule};
2 
3pub struct Slug;
4 
5impl ValidationRule for Slug {
6 async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError> {
7 match field.value.and_then(|value| value.as_str()) {
8 Some(value) if value.chars().all(|c| c.is_ascii_lowercase() || c == '-') => Ok(()),
9 _ => Err(field.reject("The :attribute field must be a slug.")),
10 }
11 }
12}
13 
14#[laravel::input]
15pub struct StoreArticle {
16 #[validate(required, max_length(100), Slug)]
17 slug: String,
18}

A custom rule is any Rust expression, such as Slug, my_package::Slug, or Slug::new().max_length(50). To add one in code, such as in a rules function, wrap it with Rule::custom(Slug).

Field gives the rule what it needs to check:

  • value is the submitted InputValue, or None when the field is missing. It holds text, numbers, booleans, arrays, objects, and uploaded files alike, so a custom rule may inspect a file with value.as_file() or read text with value.as_str().
  • name is the field's path, such as items.7.slug.
  • get("other") reads another field of the same struct, or None when the request didn't send it. In a list or map of addresses, get("country") reads the same address's country. Use "dot" notation to reach into a nested object, as in get("shipping.country").
  • input is the whole request's input, for reading a field outside the current object, such as a top-level field from inside a list entry.

Both get and input name fields as the request sends them, such as "shippingCountry" for a struct with #[serde(rename_all = "camelCase")], and return InputValue values. For example, this rule reads the country of the address it checks:

1impl ValidationRule for PostalCode {
2 async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError> {
3 let country = field.get("country").and_then(|value| value.as_str());
4 
5 // Check the postal code's format for the country...
6 
7 Ok(())
8 }
9}
1impl ValidationRule for PostalCode {
2 async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError> {
3 let country = field.get("country").and_then(|value| value.as_str());
4 
5 // Check the postal code's format for the country...
6 
7 Ok(())
8 }
9}

Return Ok(()) to accept the value, or Err(field.reject(message)) to reject it. Laravel fills in these placeholders in your rule's message:

Placeholder Value
:attribute The field's label, or its name in words, so postal_code reads "postal code"
:Attribute, :ATTRIBUTE The same name with its first letter capitalized, or in capitals
:index, :position For an item in a list, its index from 0, or its position from 1

To add placeholders of your own, build a Message and give each placeholder a value with with. For example, the PostalCode rule might name the country whose format the postal code doesn't match:

1use laravel::validation::Message;
2 
3return Err(field.reject(
4 Message::new("The :attribute doesn't match the format for :country.")
5 .with("country", country),
6));
1use laravel::validation::Message;
2 
3return Err(field.reject(
4 Message::new("The :attribute doesn't match the format for :country.")
5 .with("country", country),
6));

To replace a custom rule's message for one field, chain .message(...) onto the rule, just as you would for a built-in rule. The replacement may use your rule's placeholders too:

1#[validate(required, Slug.message("Choose a valid :attribute."))]
2slug: String,
1#[validate(required, Slug.message("Choose a valid :attribute."))]
2slug: String,

Like most built-in rules, a custom rule skips missing fields, blank strings, and null on nullable fields. To check those values too, return true from the rule's implicit method.

Asynchronous checks

Rules are async, so a rule may query the database or send an HTTP request, and return their errors with ?. Say your application keeps a BlockedDomain model of email domains it doesn't accept for sign-ups. A unique(BlockedDomain::domain) rule would compare the whole address with the column, so this rule looks up only the part after the @:

1use laravel::validation::{Field, RuleError, ValidationRule};
2 
3use crate::models::BlockedDomain;
4 
5pub struct AllowedEmailDomain;
6 
7impl ValidationRule for AllowedEmailDomain {
8 async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError> {
9 let Some((_, domain)) = field
10 .value
11 .and_then(|value| value.as_str()?.rsplit_once('@'))
12 else {
13 return Ok(());
14 };
15 
16 let blocked = BlockedDomain::query()
17 .filter(BlockedDomain::domain.eq(domain.to_lowercase()))
18 .exists()
19 .await?;
20 
21 if blocked {
22 return Err(field.reject("The :attribute uses a domain we don't accept."));
23 }
24 
25 Ok(())
26 }
27}
28 
29#[laravel::input]
30pub struct Register {
31 #[validate(bail, required, email, AllowedEmailDomain)]
32 email: String,
33}
1use laravel::validation::{Field, RuleError, ValidationRule};
2 
3use crate::models::BlockedDomain;
4 
5pub struct AllowedEmailDomain;
6 
7impl ValidationRule for AllowedEmailDomain {
8 async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError> {
9 let Some((_, domain)) = field
10 .value
11 .and_then(|value| value.as_str()?.rsplit_once('@'))
12 else {
13 return Ok(());
14 };
15 
16 let blocked = BlockedDomain::query()
17 .filter(BlockedDomain::domain.eq(domain.to_lowercase()))
18 .exists()
19 .await?;
20 
21 if blocked {
22 return Err(field.reject("The :attribute uses a domain we don't accept."));
23 }
24 
25 Ok(())
26 }
27}
28 
29#[laravel::input]
30pub struct Register {
31 #[validate(bail, required, email, AllowedEmailDomain)]
32 email: String,
33}

Put cheap rules first and add bail, so input that's already invalid never reaches the query. An error returned with ?, such as a database outage, stops validation and reaches your error handler, rather than showing up as a field error.

Testing

The application's test client has assertions for validation errors. They read the errors from a JSON response or from the session after a redirect:

1use laravel::testing::prelude::*;
2 
3#[laravel::test]
4async fn a_post_needs_a_title(app: Application) {
5 app.post("/posts")
6 .json(json!({ "title": "", "body": "Hello, world." }))
7 .await
8 .assert_status(422)
9 .assert_invalid(&["title"])
10 .assert_invalid_messages(&[("title", "required")])
11 .assert_valid(&["body"]);
12}
1use laravel::testing::prelude::*;
2 
3#[laravel::test]
4async fn a_post_needs_a_title(app: Application) {
5 app.post("/posts")
6 .json(json!({ "title": "", "body": "Hello, world." }))
7 .await
8 .assert_status(422)
9 .assert_invalid(&["title"])
10 .assert_invalid_messages(&[("title", "required")])
11 .assert_valid(&["body"]);
12}

assert_invalid_messages checks that each field has an error containing the text. assert_valid(&[]) checks that there were no errors at all. For a page with several forms, check a named form's errors with assert_invalid_in("login", &["email"]).

A browser form that fails validation goes back to the page it came from. So to test a form, send the request from that page, then check the redirect, the errors, and the input Laravel flashed to the session:

1app.post("/posts")
2 .from("/posts/create")
3 .form([("title", ""), ("body", "Hello, world.")])
4 .await
5 .assert_redirect_back_with_errors(&["title"])
6 .assert_session_has_input("body", "Hello, world.");
1app.post("/posts")
2 .from("/posts/create")
3 .form([("title", ""), ("body", "Hello, world.")])
4 .await
5 .assert_redirect_back_with_errors(&["title"])
6 .assert_session_has_input("body", "Hello, world.");

To learn more, check out the testing guide's section on redirecting back.