# Validation - [Introduction](#introduction) - [Validation quickstart](#validation-quickstart) - [Defining the input](#typed-input) - [Handling the request](#handling-the-request) - [Optional fields](#optional-fields) - [Fields a request may leave out](#fields-a-request-may-leave-out) - [Enum and ID fields](#enum-and-id-fields) - [Transforming input fields](#transforming-input-fields) - [Stopping on a field's first failure](#bail) - [Validation responses](#validation-responses) - [Displaying errors and old input](#errors-and-old-input) - [Pages with several forms](#pages-with-several-forms) - [Authorization and rules from the request](#request-hooks) - [Authorizing the request](#authorizing-the-request) - [Adding rules from the request](#adding-rules-from-the-request) - [Validating in a handler](#validating-in-a-handler) - [Adding errors after validation](#adding-errors-after-validation) - [Validating outside a request](#validating-outside-a-request) - [Filters that ignore bad values](#lenient-input) - [Available rules](#rules) - [Text and choices](#text-and-choices) - [Numbers](#numeric-bounds) - [Dates and times](#calendar-dates) - [Formats](#formats) - [Presence and acceptance](#presence-and-acceptance) - [Database records](#database-records) - [Passwords](#passwords) - [Current password](#current-password) - [Files](#files) - [Conditional rules](#conditional-rules) - [Nested objects](#nested-objects) - [Validating lists](#validating-lists) - [Contains and distinct](#contains-and-distinct) - [Custom messages and labels](#custom-messages-and-labels) - [Custom rules](#custom-rules) - [Asynchronous checks](#async-rules) - [Testing](#testing) ## 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: ```rust use laravel::prelude::*; use crate::http::handlers::posts; pub fn routes(route: &mut Router) { route.get("/posts/create", posts::create); route.post("/posts", posts::store); } ``` ### 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: ```rust use laravel::prelude::*; use crate::models::Post; #[laravel::input(fills = Post)] #[validate(anyone)] pub struct StorePost { #[validate(required, max_length(255), unique(Post::title))] title: String, #[validate(required)] body: String, } ``` 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](#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](#authorizing-the-request) 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` argument in your `store` handler. It must be the handler's last argument, because it reads the request's body: ```rust use laravel::model::create; use laravel::prelude::*; use crate::models::Post; pub async fn store(Valid(form): Valid) -> laravel::Result { let post = create!(Post { ..form }).await?; Ok(redirect!(show, post.id)) } ``` 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](models.md#fill-structs). `Valid` 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` as its last argument instead. It validates `T` as `Valid` 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: ```rust use laravel::validation::ValidRequest; pub async fn store(input: ValidRequest) -> laravel::Result { let (form, request) = input.into_parts(); let post = create!(Post { ip_address: request.ip().to_string(), ..form }).await?; Ok(redirect!(show, post.id)) } ``` 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](middleware.md) 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: ```rust #[laravel::input] pub struct StorePost { #[validate(required, max_length(255))] title: String, #[validate(date)] publish_on: Option, } ``` 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`. 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: ```rust use laravel::validation::Sometimes; #[laravel::input] #[validate(authenticated)] pub struct EditProfile { #[validate(required, max_length(255))] pub name: Sometimes, #[validate(max_length(1000))] pub bio: Sometimes>, } ``` | 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` field that the request sends must hold text, even without `required`. To let a sent field be empty, declare it `Sometimes>`, 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>` field was sent empty. When you save a [fill struct](#saving-the-input-to-a-model) 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](models.md#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](models.md#enum-columns). 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: ```rust use laravel::prelude::*; #[derive(Clone, Copy, Debug, Serialize, Deserialize, Enum)] #[serde(rename_all = "snake_case")] pub enum Visibility { Draft, Published, } #[laravel::input] pub struct StorePost { #[validate(required, max_length(255))] title: String, visibility: Visibility, } ``` 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: ```rust #[derive(Clone, Copy, Debug, Deserialize, Newtype)] pub struct CategoryId(i64); #[laravel::input] pub struct StorePost { #[validate(required, max_length(255))] title: String, #[validate(min_value(1))] category_id: CategoryId, } ``` ### 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: ```rust use laravel::prelude::*; use crate::models::User; #[laravel::input(fills = User)] #[validate(anyone)] pub struct RegisterUser { #[validate(required, max_length(255))] name: String, #[transform(lowercase)] #[validate(required, email, unique(User::email))] email: String, #[transform(uppercase)] #[validate(required, min_length(2), max_length(2))] country: String, } ``` 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 `Taylor@Example.com`, the `unique` rule queries the database for `taylor@example.com`, and your handler receives `taylor@example.com`. 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`, `ValidRequest`, `request.parse()`, `request.json()`, and `Query`. To transform a field across every request regardless of which struct binds it, use a middleware with [`transform_input`](requests.md#transforming-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: ```rust #[validate(bail, required, max_length(255), unique(Post::title))] title: 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](#presence-and-acceptance) 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](#errors-and-old-input). - An [Inertia](inertia.md#validation-errors) 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: ```json { "message": "The title field is required. (and 1 more error)", "errors": { "title": ["The title field is required."], "author.name": ["The author.name field is required."] } } ``` ## 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](inertia.md#validation-errors), Laravel populates the page's `errors` prop automatically while keeping the user's input intact. Inertia's `
` component exposes `errors` through its render prop, so you can show an individual field's message or loop through every error on the form: ```tsx import { Form } from "@inertiajs/react"; export default function CreatePost() { return ( {({ errors }) => ( <> {Object.keys(errors).length > 0 && (
    {Object.entries(errors).map(([field, message]) => (
  • {message}
  • ))}
)} {errors.title &&

{errors.title}

} )}
); } ``` #### 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: ```html {% if error('title') %}

{{ error('title') }}

{% 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: ```html {% if errors %}
    {% for field, messages in errors|items %} {% for message in messages %}
  • {{ message }}
  • {% endfor %} {% endfor %}
{% endif %} ``` To see a complete form that shows its errors, check out the templates guide's section on [validation errors and old input](templates.md#validation-errors-and-old-input). If you need old input in a handler, [`request.old::("title")`](requests.md#old-input) 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`](hashing.md#password-fields) 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`](errors.md#keeping-input-out-of-old-input). ### 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: ```rust use laravel::hash::Password; #[laravel::input] #[validate(anyone, form = "login")] pub struct Login { #[validate(required, email)] email: String, #[validate(required)] password: Password, } ``` #### Inertia Inertia pages receive a named form's errors under its name, such as `errors.login.email`. Pass `errorBag` to `
` so its `errors` render prop is scoped to that form automatically: ```tsx import { Form } from "@inertiajs/react"; export default function LoginForm() { return ( {({ errors }) => ( <> {Object.keys(errors).length > 0 && (
    {Object.entries(errors).map(([field, message]) => (
  • {message}
  • ))}
)} {errors.email &&

{errors.email}

} )}
); } ``` #### 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: ```html {% if error("email", form="login") %}

{{ error("email", form="login") }}

{% 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: ```html {% if form_errors.login %}
    {% for field, messages in form_errors.login|items %} {% for message in messages %}
  • {{ message }}
  • {% endfor %} {% endfor %}
{% endif %} ``` #### Scoping handler errors Errors that your handler returns after validation, such as with [`invalid!`](#adding-errors-after-validation), are automatically scoped to the same named form. For example, because this handler accepts `Valid`, when `auth.attempt` rejects invalid credentials, the error appears under `errors.login.email` in Inertia pages and `error("email", form="login")` in MiniJinja templates: ```rust use laravel::auth::Auth; use laravel::prelude::*; pub async fn login( auth: Auth, Valid(form): Valid, ) -> laravel::Result { auth.attempt(&form.email, &form.password).await?; Ok(Redirect::intended(dashboard::show, ())) } ``` 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 ``. 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` 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: ```rust use laravel::prelude::*; use laravel::validation::{Rule, Rules, ValidatesRequest}; #[laravel::input] pub struct UpdateTeam { #[validate(required, max_length(255))] name: String, } impl ValidatesRequest for UpdateTeam { async fn authorize(request: &Request) -> laravel::Result { let admin = request .user::() .await? .is_some_and(|user| user.is_admin); Ok(admin) } async fn rules(&self, request: &Request, rules: Rules) -> laravel::Result { let premium = request .user::() .await? .is_some_and(|user| user.is_premium); Ok(rules.field("name", [Rule::max_length(if premium { 255 } else { 50 })])) } } pub async fn update(Valid(team): Valid) -> laravel::Result { // Only admins get here, with a name that fits their plan... Ok(Redirect::back()) } ``` `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](#nested-objects) or [list item](#validating-lists) 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: ```rust #[laravel::input] pub struct UpdateTeam { #[validate(required, max_length(255))] name: String, billing_address: Address, } #[laravel::input] pub struct Address { #[validate(required, max_length(255))] street: String, #[validate(required)] city: String, } ``` ### 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`: ```rust async fn authorize(request: &Request) -> laravel::Result { let admin = request .user::() .await? .is_some_and(|user| user.is_admin); if !admin { laravel::abort!(403, "Only team admins can rename a team."); } Ok(true) } ``` 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`](authentication.md#redirecting-guests) middleware: a redirect to the login page, or a `401` for a request that expects JSON. ```rust #[laravel::input] #[validate(authenticated)] pub struct UpdateProfile { #[validate(required, max_length(255))] name: String, } ``` 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()`: ```rust impl ValidatesRequest for UpdateProfile { async fn authorize(request: &Request) -> laravel::Result { Ok(request.authenticated().await?) } async fn rules(&self, request: &Request, rules: Rules) -> laravel::Result { // Add rules that depend on the request... Ok(rules) } } ``` 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`](authentication.md#protecting-routes) middleware to the form's route. #### Authorizing with a policy When a [policy](authorization.md) 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: ```rust use crate::policies::PostPolicy; #[laravel::input] #[validate(authorize(PostPolicy::update, route("post")))] pub struct UpdatePost { #[validate(required, max_length(255))] title: String, } ``` 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](authorization.md#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: ```rust use laravel::prelude::*; use laravel::validation::{Rule, Rules, ValidatesRequest}; use crate::models::Product; #[laravel::input] pub struct StoreOrder { #[validate(required, min_value(1))] quantity: u32, } impl ValidatesRequest for StoreOrder { async fn authorize(request: &Request) -> laravel::Result { Ok(request.authenticated().await?) } async fn rules(&self, request: &Request, rules: Rules) -> laravel::Result { let product: Product = request.model("product").await?; Ok(rules.field("quantity", [Rule::max_value(product.stock)])) } } ``` 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: ```rust use laravel::prelude::*; use laravel::validation::{Rule, Rules, ValidatesRequest}; #[laravel::input] pub struct StoreWebhook { #[validate(required, one_of("http", "queue"))] kind: String, #[validate(required)] target: String, } impl ValidatesRequest for StoreWebhook { async fn authorize(request: &Request) -> laravel::Result { Ok(request.authenticated().await?) } async fn rules(&self, _request: &Request, rules: Rules) -> laravel::Result { if self.kind == "http" { Ok(rules.field("target", [Rule::url(["https"])])) } else { Ok(rules.field("target", [Rule::alpha_dash()])) } } } ``` ## Validating in a handler Most handlers take `Valid`. If you'd like to decide what happens when validation fails, take the `Request` instead and call `request.validate::()`. 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: ```rust use laravel::prelude::*; pub async fn store(request: Request) -> laravel::Result { let form: StorePost = request.validate().await?; // Store the post... Ok(Redirect::back()) } ``` 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: ```rust use laravel::prelude::*; use laravel::validation::ValidationError; pub async fn store(request: Request) -> laravel::Result { let form = match request.validate::().await { Ok(form) => form, Err(ValidationError::Invalid(errors)) => { return Ok(view("posts.create", data! {}) .with_errors(errors) .with_input(&request) .fragment("form") .with_status(StatusCode::UNPROCESSABLE_ENTITY) .into_response()); } Err(ValidationError::Failed(error)) => return Err(error), }; // Store the post... Ok(redirect!(index).into_response()) } ``` `ValidationError::Invalid` holds the field errors. `ValidationError::Failed` holds an error that stopped validation, such as a database outage in a [`unique` rule](#database-records). 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: ```rust use laravel::prelude::*; use laravel::time::civil::Date; use laravel::validation::invalid; use crate::models::{Booking, Room}; #[laravel::input] #[validate(authenticated)] pub struct StoreBooking { #[validate(required, exists(Room::id))] room_id: i64, #[validate(required, label = "arrival date")] starts_on: Date, #[validate(required, after(starts_on), label = "departure date")] ends_on: Date, } pub async fn store(Valid(form): Valid) -> laravel::Result { let taken = Booking::query() .filter(Booking::room_id.eq(form.room_id)) .filter(Booking::starts_on.lt(form.ends_on)) .filter(Booking::ends_on.gt(form.starts_on)) .exists() .await?; if taken { invalid!(starts_on => "The room is already booked for some of those dates."); } // Store the booking... Ok(redirect!(bookings::index)) } ``` 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: ```rust invalid!( password => ["The password is too common.", "The password appeared in a data breach."], "items.0.quantity" => "Only 3 are left in stock.", format!("members.{index}.user_id") => "This user is already a member.", ); ``` 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: ```rust use laravel::validation::InvalidInput; use crate::models::Product; pub async fn store(Valid(order): Valid) -> laravel::Result { let mut errors = InvalidInput::new(); for (index, item) in order.items.iter().enumerate() { let product = Product::find_or_fail(item.product_id).await?; if i64::from(item.quantity) > product.stock { errors.add( format!("items.{index}.quantity"), format!("Only {} are left in stock.", product.stock), ); } } if !errors.is_empty() { return Err(errors.into()); } // Store the order... Ok(redirect!(orders::index)) } ``` To send the user somewhere other than back to the form, such as to their cart, redirect with the errors yourself: ```rust return Ok(redirect!(cart::show).with_errors(errors)); ``` On a page with [several forms](#pages-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`: ```rust use laravel::validation::{Validate, ValidationError}; #[derive(Validate)] struct ImportedPost { #[validate(required, max_length(255))] title: String, #[validate(required)] body: String, } pub async fn import_row(row: &[String]) -> laravel::Result<()> { let post = ImportedPost { title: row[0].clone(), body: row[1].clone(), }; match post.validate().await { Ok(()) => { // Store the post... } Err(ValidationError::Invalid(errors)) => { for (field, messages) in errors.errors() { for message in messages { println!("{field}: {message}"); } } } Err(ValidationError::Failed(error)) => return Err(error), } Ok(()) } ``` `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!`: ```rust use laravel::model::{Fill, create}; use laravel::prelude::*; use laravel::validation::Validate; use crate::models::{Post, User}; #[derive(Validate, Fill)] #[fills(Post)] struct ImportedPost { #[validate(required, max_length(255))] title: String, #[validate(required)] body: String, } pub async fn import(Authenticated(user): Authenticated) -> laravel::Result { let input = ImportedPost { title: "Imported post".into(), body: "Post contents...".into(), }; input.validate().await?; let post = create!(Post { user: &user, ..input }).await?; Ok(redirect!(posts::show, &post)) } ``` To learn more about `Fill` structs, check out the models guide's section on [fill structs](models.md#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`. Every field with a fallback (`Option`, `#[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: ```rust use laravel::inertia::{self, Page, props}; use laravel::prelude::*; #[derive(Deserialize, Serialize, Enum)] #[serde(rename_all = "snake_case")] pub enum Priority { Low, High, } #[laravel::query] #[derive(Serialize)] pub struct IssueFilters { priority: Option, assignee: Option, #[default] #[validate(max_length(100))] q: String, #[default = 1] #[validate(min_value(1))] page: u32, #[default] labels: Vec, } pub async fn index(Query(filters): Query) -> Page { // Query the issues that match the filters... inertia::render("Issues/Index", props! { filters }) } ``` `/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](requests.md#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: ```rust #[laravel::input] pub struct StorePost { #[validate(required, max_length(100))] title: String, #[validate(required, one_of("draft", "published"))] status: String, } ``` When you add rules in code instead, such as in a [`rules` function](#adding-rules-from-the-request), 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: ```rust rules .field("title", [Rule::required(), Rule::max_length(100)]) .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 `_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: ```rust #[laravel::input] pub struct StoreOrder { #[validate(required, min_value(1), max_value(100))] quantity: u32, #[validate(between(0.0, 5.0))] rating: Option, } ``` `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: ```rust #[laravel::input] pub struct PriceRange { #[validate(required, min_value(0), label = "minimum price")] minimum: u64, #[validate(required, gte(minimum), label = "maximum price")] maximum: u64, } ``` #### 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: ```rust use laravel::numeric::Decimal; #[laravel::input] pub struct StoreProduct { #[validate(required, decimal(2), min_value(0))] price: Decimal, #[validate(required, multiple_of(12))] quantity: u32, } ``` For money and other exact amounts, use `laravel::numeric::Decimal` rather than `f64`. `Valid` decodes form text and JSON numbers into a `Decimal` without rounding them, and [databases](database.md#decimals) 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 `` submits a date such as `2024-02-29`. Declare the field as a [`laravel::time::civil::Date`](time.md), and Laravel checks that the value is a real calendar date, as the `date` rule does. Your handler then receives a typed date: ```rust use laravel::time::civil::Date; #[laravel::input] pub struct StoreBooking { #[validate(required, today_or_after, label = "arrival date")] starts_on: Date, #[validate(required, after_or_equal(starts_on), label = "departure date")] ends_on: Date, } ``` 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](time.md#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`](time.md) 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: ```rust use laravel::time::Timestamp; #[laravel::input] pub struct StoreAppointment { #[validate(required, label = "start time")] starts_at: Timestamp, #[validate(required, after(starts_at), label = "end time")] ends_at: Timestamp, } ``` > [!NOTE] > An HTML `` 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](https://docs.rs/jiff/latest/jiff/fmt/strtime/index.html) 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: ```rust use laravel::time::civil::Date; use laravel::validation::Valid; #[laravel::input] #[validate(authenticated)] pub struct UpdateProfile { #[validate(required, date_format("%d/%m/%Y"))] birthday: String, } pub async fn update(Valid(form): Valid) -> laravel::Result { let birthday = Date::strptime("%d/%m/%Y", &form.birthday)?; // Store the birthday... Ok(Redirect::back()) } ``` 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: ```rust #[laravel::input] pub struct UpdateContact { #[validate(required, email)] email: String, #[validate(url)] website: Option, #[validate(url("https").message("Please enter an HTTPS callback URL."))] callback: Option, } ``` 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: ```rust use std::net::IpAddr; use laravel::str::Uuid; #[laravel::input] pub struct StoreDevice { device_id: Uuid, address: IpAddr, } ``` Use the rules on `String` fields, or to require a UUID version, as in `uuid(7)`. #### Regular expressions Patterns use [Rust regex syntax](https://docs.rs/regex/latest/regex/#syntax), without `/` delimiters. A pattern matches anywhere in the text, so anchor it with `\A` and `\z` to match the whole value: ```rust #[laravel::input] pub struct StoreProduct { #[validate(required, regex(r"\A[A-Z]{3}-[0-9]{4}\z"))] sku: String, } ``` 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](#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.": ```rust use laravel::hash::Password; #[laravel::input] pub struct Register { #[validate(required, email)] email: String, #[validate(required, password, confirmed)] password: Password, #[validate(accepted)] terms: bool, #[serde(default)] newsletter: bool, } ``` ### 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](models.md) to check: ```rust use crate::models::{Category, Post, Tag}; #[laravel::input] pub struct StorePost { #[validate(required, max_length(255), unique(Post::slug))] slug: String, #[validate(required, exists(Category::id))] category_id: i64, #[validate(bail, max_items(20), each(exists(Tag::id)))] tag_ids: Vec, } ``` The rules query the model's table on the model's [database connection](database.md). 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 `Taylor@example.com` when the row has `taylor@example.com`, 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](#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: ```rust #[laravel::input] pub struct UpdateProfile { #[validate(required, email, unique(User::email, ignore = user))] email: String, } ``` 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: ```rust use laravel::model::update; use laravel::prelude::*; use crate::models::Team; #[laravel::input(fills = Team)] #[validate(authenticated)] pub struct UpdateTeam { #[validate(required, unique(Team::name, ignore = route("team")))] name: String, } // PUT /teams/{team} pub async fn update( mut team: Team, Valid(input): Valid, ) -> laravel::Result { update!(team { ..input }).await?; Ok(Redirect::back()) } ``` 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](authentication.md). When the ID comes from somewhere else, add the rule with `Rule::unique(..).ignore(id)` in a [`rules` function](#adding-rules-from-the-request), or check the record in your handler and return an error with [`invalid!`](#adding-errors-after-validation). #### 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](queries.md#conditions). For example, this rule only accepts categories that aren't archived: ```rust use crate::models::Category; #[laravel::input] pub struct StorePost { #[validate(required, exists(Category::id, filter = Category::archived_at.is_null()))] category_id: i64, } ``` 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](models.md#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")` in the condition. The rule finds the project that `{project}` names and compares the column with its key: ```rust use laravel::prelude::*; use crate::models::{Label, Project}; #[laravel::input] #[validate(authenticated)] pub struct StoreIssue { #[validate(required, max_length(255))] title: String, #[serde(default)] #[validate( max_items(10), each(exists(Label::id, filter = Label::project_id.eq(route::("project")))), )] label_ids: Vec, } // POST /projects/{project}/issues pub async fn store( project: Project, Valid(input): Valid, ) -> laravel::Result { // Create the issue... Ok(Redirect::back()) } ``` 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](#adding-rules-from-the-request). 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: ```rust use laravel::prelude::*; use laravel::validation::{Rule, Rules, ValidatesRequest}; use crate::models::Member; #[laravel::input] pub struct StoreInvitation { #[validate(required, email)] email: String, } impl ValidatesRequest for StoreInvitation { async fn authorize(request: &Request) -> laravel::Result { Ok(request.authenticated().await?) } async fn rules(&self, request: &Request, rules: Rules) -> laravel::Result { let team: i64 = request .route("team") .and_then(|id| id.parse().ok()) .or_abort(404)?; Ok(rules.field( "email", [Rule::unique(Member::email).filter(Member::team_id.eq(team))], )) } } ``` `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: ```rust rules.field( "email", ( Rule::max_length(255), Rule::unique(Member::email).filter(Member::team_id.eq(team)), ), ) ``` ### 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: ```rust use laravel::hash::Password; #[laravel::input] pub struct ResetPassword { #[validate(required, email)] email: String, #[validate(required, password, confirmed)] password: Password, } ``` 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`: ```rust use laravel::validation::PasswordRule; Application::configure() .with_services(|app| { app.instance(PasswordRule::min(8).letters().mixed_case().numbers()); }) ``` | 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: ```rust #[validate(required, password(min = 12, symbols), confirmed)] password: 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: ```rust use laravel::hash::Password; #[laravel::input] pub struct UpdatePassword { #[validate(required, current_password)] current_password: Password, #[validate(required, password, confirmed)] password: Password, } ``` 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](authentication.md). 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](hashing.md#password-fields). ### Files To validate an [uploaded file](requests.md#files), 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: ```rust use laravel::http::UploadedFile; use laravel::prelude::*; #[laravel::input] #[validate(authenticated)] pub struct UpdateProfile { #[validate(required, max_length(255))] name: String, #[validate(required, image, max_kilobytes(2048))] avatar: UploadedFile, #[validate(mimes("pdf"), max_kilobytes(10240))] resume: Option, } pub async fn update(Valid(form): Valid) -> laravel::Result { let path = form.avatar.store("avatars").disk("public").await?; // Save the avatar's path... Ok(Redirect::back()) } ``` Use `Option` for an optional file. For an `` named `photos[]`, use `Vec`, 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.md#body-size) 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: ```rust #[laravel::input] pub struct StoreShipment { #[validate(required, one_of("ship", "pickup"))] delivery: String, #[validate(required_if(delivery, "ship"))] address: Option, #[validate(prohibited_if(delivery, "ship"))] pickup_notes: Option, } ``` | 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](#presence-and-acceptance) | | `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: ```rust #[laravel::input] pub struct StoreShipments { #[validate(required)] addresses: Vec
, } #[laravel::input] pub struct Address { #[validate(required)] country: String, #[validate(required_if(country, "US"))] state: Option, } ``` 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: ```rust #[laravel::input] pub struct StoreOrder { shipping: Address, #[validate(required_if(shipping.country, "US"))] phone: Option, } ``` 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: ```rust #[laravel::input] #[serde(rename_all = "camelCase")] pub struct StoreOrder { shipping_country: String, #[validate(required_if(shipping_country, "US"))] phone_number: Option, } ``` Rules you add in code, such as in a [`rules` function](#adding-rules-from-the-request), 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 ``. 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: ```rust #[laravel::input] pub struct StoreOrder { shipping: Address, billing: Option
, } #[laravel::input] pub struct Address { #[validate(required, max_length(255))] street: String, #[validate(required)] city: String, country: String, #[validate(required_if(country, "US"))] postal_code: Option, } ``` 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`): ```rust use std::collections::HashMap; #[laravel::input] #[validate(anyone)] pub struct UpdateContact { #[validate(allowed_keys("name", "email"), required_keys("email"))] contact: HashMap>, } ``` 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: ```rust use std::collections::HashMap; #[laravel::input] #[validate(anyone)] pub struct StorePost { #[validate(required, each(required, max_length(255)))] titles: HashMap, } ``` 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(...)`: ```rust use crate::models::Product; #[laravel::input] pub struct StoreOrder { #[validate(required, max_items(50))] items: Vec, #[validate(max_items(10), distinct, each(required, max_length(50)))] tags: Vec, } #[laravel::input] pub struct OrderItem { #[validate(required, exists(Product::id))] product_id: i64, #[validate(required, min_value(1))] quantity: u32, } ``` 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>` accepts a missing list, and `Vec>` 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` or `Vec`, they compare the decoded numeric or boolean values so `"1"` and `1` match: ```rust #[laravel::input] pub struct UpdateRoles { #[validate(required, contains("member"), doesnt_contain("owner"), distinct)] roles: Vec, } ``` ## 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: ```rust #[laravel::input] pub struct StoreUser { #[validate( required.message("Please enter your :attribute."), email, label = "email address", )] email: String, } ``` 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: ```rust #[laravel::input] pub struct StoreArticle { #[validate( max_items(10).message("Choose at most :max tags."), distinct.message("Choose a different name for each tag."), each( required.message("Tag #:position can't be blank."), max_length(50).message(":Attribute #:position must be at most :max characters."), ) .label("tag"), )] tags: Vec, } ``` 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): ```rust use laravel::str::Uuid; #[laravel::input] pub struct StoreTickets { #[validate(invalid = "Enter a whole number of tickets.")] quantity: u32, #[validate(invalid = "That event ID isn't valid.")] event_id: Uuid, } ``` 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: ```rust use laravel::validation::{Field, RuleError, ValidationRule}; pub struct Slug; impl ValidationRule for Slug { async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError> { match field.value.and_then(|value| value.as_str()) { Some(value) if value.chars().all(|c| c.is_ascii_lowercase() || c == '-') => Ok(()), _ => Err(field.reject("The :attribute field must be a slug.")), } } } #[laravel::input] pub struct StoreArticle { #[validate(required, max_length(100), Slug)] slug: String, } ``` 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](#adding-rules-from-the-request), 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: ```rust impl ValidationRule for PostalCode { async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError> { let country = field.get("country").and_then(|value| value.as_str()); // Check the postal code's format for the country... Ok(()) } } ``` 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: ```rust use laravel::validation::Message; return Err(field.reject( Message::new("The :attribute doesn't match the format for :country.") .with("country", country), )); ``` 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: ```rust #[validate(required, Slug.message("Choose a valid :attribute."))] slug: 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 `@`: ```rust use laravel::validation::{Field, RuleError, ValidationRule}; use crate::models::BlockedDomain; pub struct AllowedEmailDomain; impl ValidationRule for AllowedEmailDomain { async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError> { let Some((_, domain)) = field .value .and_then(|value| value.as_str()?.rsplit_once('@')) else { return Ok(()); }; let blocked = BlockedDomain::query() .filter(BlockedDomain::domain.eq(domain.to_lowercase())) .exists() .await?; if blocked { return Err(field.reject("The :attribute uses a domain we don't accept.")); } Ok(()) } } #[laravel::input] pub struct Register { #[validate(bail, required, email, AllowedEmailDomain)] email: String, } ``` 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](testing.md) has assertions for validation errors. They read the errors from a JSON response or from the session after a redirect: ```rust use laravel::testing::prelude::*; #[laravel::test] async fn a_post_needs_a_title(app: Application) { app.post("/posts") .json(json!({ "title": "", "body": "Hello, world." })) .await .assert_status(422) .assert_invalid(&["title"]) .assert_invalid_messages(&[("title", "required")]) .assert_valid(&["body"]); } ``` `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](#pages-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: ```rust app.post("/posts") .from("/posts/create") .form([("title", ""), ("body", "Hello, world.")]) .await .assert_redirect_back_with_errors(&["title"]) .assert_session_has_input("body", "Hello, world."); ``` To learn more, check out the testing guide's section on [redirecting back](testing.md#redirecting-back).