Validation
- Introduction
- Validation quickstart
- Displaying errors and old input
- Authorization and rules from the request
- Validating in a handler
- Available rules
- Conditional rules
- Nested objects
- Validating lists
- Custom messages and labels
- Custom rules
- Validating data without a request
- 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 Go struct and give its fields rules. Your handler fills the struct from the request in one call, and only carries on 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 routes/web.go, one route shows the form for a new post, and another stores the post once the user submits the form:
package routes
import (
"go.laravel.com/config"
"go.laravel.com/routing"
"app/handlers/posts"
)
func Web(route *routing.Router, cfg *config.Config) {
route.Get("/posts/create", posts.Create).Name("posts.create")
route.Post("/posts", posts.Store).Name("posts.store")
}Defining the input
Next, in the package that holds your post handlers, describe the form's input as a struct with json tags, as you would for r.Bind. Then give the struct a Rules method that attaches rules to its fields with validation.For and rule.Field:
package posts
import (
"go.laravel.com/model"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
"app/models"
)
type StorePost struct {
Title string `json:"title"`
Body string `json:"body"`
}
func (f *StorePost) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Title, rule.Required, rule.Max(255), model.Unique[models.Post]()),
rule.Field(&f.Body, rule.Required),
)
}Laravel checks each field's rules in the order you write them, and matches each field pointer to its json tag name when reading input and reporting errors. Because each field is referenced by its struct pointer (&f.Title), misspelled field names fail to compile. To learn more about the rules you may use, check out the available rules.
You don't need a rule for a field's Go type, because Laravel checks the type for you. A string field accepts only text, and an int field accepts only whole numbers. For example, age=abc fails with "The age field must be an integer.", and the field's other rules don't run.
Handling the request
Now call r.Validate with the struct's type in your Store handler. Validate fills the struct from the request and checks the input against the rules. If the input fails, Validate returns an error that you pass to web.Fail as it is:
package posts
import (
"go.laravel.com/model"
"go.laravel.com/web"
"app/models"
)
func Store(r *web.Request) *web.Response {
form, err := r.Validate[StorePost]()
if err != nil {
return web.Fail(err)
}
post := models.Post{Title: form.Title, Body: form.Body}
if err := model.Create(r, &post); err != nil {
return web.Fail(err)
}
return web.RedirectRoute("posts.show", "post", post.ID)
}The rest of your Store handler only runs when the input fits the struct and passes every rule. If it doesn't, web.Fail sends the user back to the form with the errors, and your handler never creates the post.
Copy each field you allow into the model yourself, as this handler does with Title and Body. The struct literal you write lists the only columns a request may set, so a user can't add is_admin=1 to the form and change a column you never showed them. Don't validate input into the model struct itself, because then the request may set every field of the model. To learn more, check out the models guide's section on taking values from a form.
Optional fields
If the user may leave a field empty, such as a post's excerpt, leave out rule.Required. Laravel's default TrimStrings and ConvertEmptyStrings middleware turn an empty text input into null before validation runs. If the user does fill in the field, the field's other rules still check the value:
type StorePost struct {
Title string `json:"title"`
Excerpt *string `json:"excerpt"`
}
func (f *StorePost) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Title, rule.Required, rule.Max(255)),
rule.Field(&f.Excerpt, rule.Max(500)),
)
}Ordinary rules, such as Max and Date, skip a field that's missing, blank, or null. Add rule.Required when an empty value should fail. If your handler needs to tell a field the user left empty from an empty string, declare the field as a pointer, as Excerpt is. The pointer is nil when the user left the field empty.
Fields a request may leave out
A pointer 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 validation.Sometimes[T]. When the request leaves a field out, its Present is false, and validation skips all of its rules, rule.Required included. When the request sends the field, Present is true, Value holds what it sent, and its rules run as usual:
package profile
import (
"go.laravel.com/db"
"go.laravel.com/model"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
"go.laravel.com/web"
"app/models"
)
type EditProfile struct {
Name validation.Sometimes[string] `json:"name"`
Bio validation.Sometimes[*string] `json:"bio"`
}
func (f *EditProfile) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Name, rule.Required, rule.Max(255)),
rule.Field(&f.Bio, rule.Max(1000)),
)
}
func Update(r *web.Request) *web.Response {
form, err := r.Validate[EditProfile]()
if err != nil {
return web.Fail(err)
}
user := r.User[models.User]()
if err := model.Update(r, user, db.Values{
"name": form.Name,
"bio": form.Bio,
}); err != nil {
return web.Fail(err)
}
return web.Back()
}| The request | Name | Bio |
|---|---|---|
| Leaves out both fields | Not present | Not present |
Sends name as "Taylor" | Present, "Taylor" | Not present |
Sends bio as null or blank | Not present | Present, nil |
Sends name as null or blank | Fails: "The name field is required." | Not present |
So rule.Required on a Sometimes field means "not empty, if sent". A field that can't hold null, such as a Sometimes[int] quantity, fails as required when the request sends null, because the rules would otherwise skip the null and your handler would write a 0 that Min never checked. If null should clear the field, declare it as a pointer, as Bio is. You may pass Sometimes fields directly into db.Values: Laravel writes the fields the request sent and leaves out the ones it didn't. When you need to inspect a field yourself, Get returns its value and whether the request sent it. When a Sometimes field holds a struct, a missing field also skips that struct's rules, so an Address's rules apply only when the request sends an address.
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 a transform:"lowercase" or transform:"uppercase" tag to any string field on an input struct:
package auth
import (
"go.laravel.com/model"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
"app/models"
)
type RegisterUser struct {
Name string `json:"name"`
Email string `json:"email" transform:"lowercase"`
Country string `json:"country" transform:"uppercase"`
}
func (f *RegisterUser) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Name, rule.Required, rule.Max(255)),
rule.Field(&f.Email, rule.Required, rule.Email, model.Unique[models.User]()),
rule.Field(&f.Country, rule.Required, rule.Size(2)),
)
}Laravel runs the transform tag while binding the request into the struct, before Rules, validation rules, and your handler see the value. If a user submits Taylor@Example.com, model.Unique 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.
The transform tag supports string fields (and defined string types), as well as pointers, validation.Sometimes, slices, arrays, and maps of strings. It applies across r.Validate, r.Bind, r.Query, and their *Into variants. To transform a field across every request regardless of which struct binds it, use a middleware with r.Transform 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, put rule.Bail first in the field's rules. In this example, if the title is longer than 255 characters, the Unique rule never queries the database:
rule.Field(&f.Title,
rule.Bail,
rule.Required,
rule.Max(255),
model.Unique[models.Post](),
)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 rule.Required fails, Laravel skips the rest of that field's rules even without Bail.
Validation responses
When validation fails and you pass the error to web.Fail, Laravel responds based on the kind of request:
- A browser form on a route in the
webgroup 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
errorsprop. - A request that expects JSON, or a route in the
apigroup, gets a422 Unprocessable Contentwith the errors as JSON. - A browser request to a route without a session can't carry errors through a redirect, so it gets the
422error 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:
{
"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, 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:
import { Form } from "@inertiajs/react";
export default function CreatePost() {
return (
<Form action="/posts" method="post">
{({ errors }) => (
<>
{Object.keys(errors).length > 0 && (
<ul className="errors">
{Object.entries(errors).map(([field, message]) => (
<li key={field}>{message}</li>
))}
</ul>
)}
<label htmlFor="title">Title</label>
<input id="title" name="title" />
{errors.title && <p className="error">{errors.title}</p>}
</>
)}
</Form>
);
}Templates
When rendering server-side views, 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:
<!-- resources/views/posts/create.html -->
<form method="POST" action="{{route "posts.store"}}">
{{csrfField}}
<label for="title">Title</label>
<input id="title" name="title" value="{{old "title"}}">
{{with error "title"}}<p class="error">{{.}}</p>{{end}}
<button>Publish</button>
</form>Views read the errors and old input from the session, so the handler that shows the form doesn't pass them to the view:
func Create(r *web.Request) *web.Response {
return web.View("posts.create", nil)
}old takes a default value as its second argument, which an edit form uses for the record's current value, as in {{old "title" .Post.Title}}. The field shows that value until the user submits the form, and what the user typed after a failed submission.
Your views may also read every error with errors, in the order your form's struct declares the fields. To list every message above the form, loop over the fields and their messages:
{{with errors}}
<ul class="errors">
{{range .}}{{range .Messages}}<li>{{.}}</li>{{end}}{{end}}
</ul>
{{end}}To see a complete form that shows its errors, including select menus and checkboxes, check out the templates guide's section on validation errors and old input.
If you need the errors or old input in a handler, r.Session().Errors("") returns the errors, and r.Session().OldInput("title") returns a field's submitted value and whether the request sent it.
Old input never includes passwords or uploaded files, so the user enters those again. Laravel leaves out any field named password, password_confirmation, or current_password. To keep other fields out of the session, such as a card number, list them in DontFlash.
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, give each form's errors a bag of their own to keep them apart. Validate with r.ValidateIn and the bag's name:
form, err := r.ValidateIn[Login]("login")
if err != nil {
return web.Fail(err)
}Inertia
Inertia pages receive a named bag'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:
import { Form } from "@inertiajs/react";
export default function LoginForm() {
return (
<Form action="/login" method="post" errorBag="login">
{({ errors }) => (
<>
{Object.keys(errors).length > 0 && (
<ul className="errors">
{Object.entries(errors).map(([field, message]) => (
<li key={field}>{message}</li>
))}
</ul>
)}
<label htmlFor="email">Email</label>
<input id="email" name="email" type="email" />
{errors.email && <p className="error">{errors.email}</p>}
</>
)}
</Form>
);
}Templates
In a template, pass the bag's name to error or errors to read that form's messages. Without a name, they read the default bag, where r.Validate puts its errors:
{{with error "email" "login"}}<p class="error">{{.}}</p>{{end}}To list every message for a named form, pass the bag's name to errors:
{{with errors "login"}}
<ul class="errors">
{{range .}}{{range .Messages}}<li>{{.}}</li>{{end}}{{end}}
</ul>
{{end}}Error bags separate messages, not old input, so use distinct field names when two forms on the same page both restore their values with old.
Scoping handler errors
Additional errors that the handler reports after r.ValidateIn go in the same bag. For example, when auth.Attempt rejects the login form's password, or a rate limit's On method turns too many attempts into an error, the message lands in the login bag next to the form's other errors.
Dynamic form names
When a page repeats one form per item, such as an inline edit form for each comment, include a hidden _form input with a unique name like comment-42. r.Validate automatically uses _form as the error bag and leaves it out of old input. JSON responses don't name the bag.
Authorization and rules from the request
Sometimes a form needs more than fixed 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 validates the form, give the form type an Authorize method, a Rules method that takes the request, or both.
Validate calls Authorize first, before it binds the input, and calls Rules once the input is bound. Say each User has an IsAdmin flag and an IsPremium plan. Only admins may rename their team, and premium teams get longer names:
package teams
import (
"go.laravel.com/auth"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
"go.laravel.com/web"
"app/models"
)
type UpdateTeam struct {
Name string `json:"name"`
}
func (UpdateTeam) Authorize(r *web.Request) error {
user := r.User[models.User]()
return auth.Allow(user != nil && user.IsAdmin)
}
func (f *UpdateTeam) Rules(r *web.Request) (validation.Rules, error) {
limit := 50
if user := r.User[models.User](); user != nil && user.IsPremium {
limit = 255
}
return validation.For(f,
rule.Field(&f.Name, rule.Required, rule.Max(limit)),
), nil
}
func Update(r *web.Request) *web.Response {
form, err := r.Validate[UpdateTeam]()
if err != nil {
return web.Fail(err)
}
// Only admins get here, with a name that fits their plan...
return web.Back()
}Both methods are optional, and a form has one Rules method, which takes the request or takes nothing. When Rules can't build the rules, such as when a query fails, it returns the error, and Validate returns that error too.
Authorizing the request
Authorize runs before validation. If it returns an error, Validate returns that error without validating the input, so a stranger who submits the form sees a 403 rather than validation errors. auth.Allow(false) fails with a 403 and the message "This action is unauthorized."
To tell the user why you rejected the request, return auth.Deny with your own message. For example, this form lets only a team's owner rename the team, finding the team from the route's {team} parameter:
func (RenameTeam) Authorize(r *web.Request) error {
team, err := model.FromRoute[models.Team](r, "team")
if err != nil {
return err
}
user := r.User[models.User]()
if user == nil || user.ID != team.OwnerID {
return auth.Deny("Only the team's owner can rename it.")
}
return nil
}If any logged-in user may submit a form, such as a comment form, return auth.Authenticated(r). A guest gets the same response as from the auth.Authenticate middleware: a redirect to the login page, or a 401 for a request that expects JSON:
func (StoreComment) Authorize(r *web.Request) error {
return auth.Authenticated(r)
}Authorizing with a policy
When a policy decides who may submit a form, return auth.Authorize with the policy's ability from Authorize. On a route such as PUT /posts/{post}, find the post, then check whether the current user may update it:
func (UpdatePost) Authorize(r *web.Request) error {
post, err := model.FromRoute[models.Post](r, "post")
if err != nil {
return err
}
return auth.Authorize(r, policies.UpdatePost(&post))
}A denial gets the policy's response, such as a 403 with its message. 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 field. An order shouldn't ask for more than the product has in stock. To find the product in your Rules method, call model.FromRoute with the route parameter's name:
package orders
import (
"go.laravel.com/model"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
"go.laravel.com/web"
"app/models"
)
type StoreOrder struct {
Quantity int `json:"quantity"`
}
func (f *StoreOrder) Rules(r *web.Request) (validation.Rules, error) {
product, err := model.FromRoute[models.Product](r, "product")
if err != nil {
return validation.Rules{}, err
}
return validation.For(f,
rule.Field(&f.Quantity, rule.Required, rule.Min(1), rule.Max(product.Stock)),
), nil
}If no product has the ID in the URL, the request gets a 404.
Rules may also read the form's own fields, because Validate binds the input before it calls Rules. For example, an uptime monitor checks its target as a URL for an HTTP monitor, and as a host name for a ping monitor:
type StoreMonitor struct {
Kind string `json:"kind"`
Target string `json:"target"`
}
func (f *StoreMonitor) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Kind, rule.Required, rule.In("http", "ping")),
rule.Field(&f.Target,
rule.Required,
rule.When(f.Kind == "http", rule.URL),
rule.When(f.Kind != "http", rule.Regex(`^[A-Za-z0-9.-]+$`)),
),
)
}Validating in a handler
Most handlers pass a validation error to web.Fail. If you'd like to decide what happens when validation fails, look for a *web.InputError with errors.AsType. For example, a coupon form in a page's sidebar might send the shopper to their cart rather than back to the previous page. This handler flashes the errors and the input, then redirects to /cart:
package coupons
import (
"errors"
"go.laravel.com/web"
)
func Apply(r *web.Request) *web.Response {
form, err := r.Validate[ApplyCoupon]()
if invalid, ok := errors.AsType[*web.InputError](err); ok {
return web.Redirect("/cart").WithErrors(invalid).WithInput()
}
if err != nil {
return web.Fail(err)
}
// Apply the coupon using form...
return web.Redirect("/cart")
}An InputError's Fields holds the field errors, and its Bag names the form's bag. Chaining WithErrors onto a redirect flashes those errors to the session for the next request. Any other error means validation couldn't finish, such as a database outage during a Unique rule. Pass that error to web.Fail, so that Laravel reports it.
Adding rules in the handler
Sometimes a rule needs a value that only the handler has, such as the team the handler loaded. Give the form an unexported field for the value, set the field on a struct value, and pass its pointer to r.ValidateInto. Binding the input leaves unexported fields alone, so Rules reads the value you set. For example, this form ignores the team's own row when it checks that the name is unique:
package teams
import (
"go.laravel.com/model"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
"go.laravel.com/web"
"app/models"
)
type RenameTeam struct {
Name string `json:"name"`
team models.Team
}
func (f *RenameTeam) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Name,
rule.Required,
rule.Max(255),
model.Unique[models.Team]().Ignore(f.team),
),
)
}
func Rename(r *web.Request) *web.Response {
team, err := model.FromRoute[models.Team](r, "team")
if err != nil {
return web.Fail(err)
}
form := RenameTeam{team: team}
if err := r.ValidateInto(&form); err != nil {
return web.Fail(err)
}
// Rename the team...
return web.Back()
}ValidateInto still runs the form's Authorize method first. If validation fails, 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. (ValidateInInto offers the same pointer form for named bags.)
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 web.Invalid with the field and its message. 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:
package bookings
import (
"go.laravel.com/date"
"go.laravel.com/model"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
"go.laravel.com/web"
"app/models"
)
type StoreBooking struct {
RoomID int64 `json:"room_id"`
StartsOn date.Date `json:"starts_on"`
EndsOn date.Date `json:"ends_on"`
}
func (f *StoreBooking) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.RoomID, rule.Required, model.Exists[models.Room]()),
rule.Field(&f.StartsOn, rule.Required),
rule.Field(&f.EndsOn, rule.Required, rule.After(&f.StartsOn)),
)
}
func Store(r *web.Request) *web.Response {
form, err := r.Validate[StoreBooking]()
if err != nil {
return web.Fail(err)
}
taken, err := model.Query[models.Booking]().
WhereEq("room_id", form.RoomID).
WhereLt("starts_on", form.EndsOn).
WhereGt("ends_on", form.StartsOn).
Exists(r)
if err != nil {
return web.Fail(err)
}
if taken {
return web.Invalid("starts_on", "The room is already booked for some of those dates.")
}
// Store the booking...
return web.RedirectRoute("bookings.index")
}To add an error to a nested field, name the field by its path, with dots between its levels, such as items.0.quantity.
If you'd like to collect errors as you go, declare a validation.Errors and call Add with a field's path and a message for each problem you find. A field may get several messages. Pass the collected errors to web.InvalidErrors, and 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:
func Store(r *web.Request) *web.Response {
form, err := r.Validate[StoreOrder]()
if err != nil {
return web.Fail(err)
}
var invalid validation.Errors
for i, item := range form.Items {
product, err := model.Find[models.Product](r, item.ProductID)
if err != nil {
return web.Fail(err)
}
if item.Quantity > product.Stock {
invalid.Add(
fmt.Sprintf("items.%d.quantity", i),
fmt.Sprintf("Only %d are left in stock.", product.Stock),
)
}
}
if len(invalid) > 0 {
return web.InvalidErrors(invalid)
}
// Store the order...
return web.RedirectRoute("orders.index")
}If the page has several forms, set the error's Bag to the form's bag, as in &web.InputError{Bag: "booking", Fields: invalid}.
To validate query string parameters (such as search filters that drop bad values, or required OAuth callback parameters), use r.Query.
Available rules
The sections below list every rule Laravel includes, grouped by the kind of value each rule checks. The rules are in the go.laravel.com/validation/rule package. You call a rule that takes settings as a function, such as rule.Max(100), and use a rule without settings as a value, such as rule.Required:
func (f *StorePost) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Title, rule.Required, rule.Max(100)),
rule.Field(&f.Status, rule.Required, rule.In("draft", "published")),
)
}Most rules skip a field that's missing, blank, or null, so add rule.Required to a field that must have a value.
Text and choices
| Rule | Passes when the value is |
|---|---|
Min(3) | Text of at least 3 characters, for a string field |
Max(255) | Text of at most 255 characters, for a string field |
In("draft", "published") | One of the choices. A list passes when every item is one |
NotIn("admin", "root") | None of the choices |
Confirmed | The same as the <name>_confirmation field, such as password_confirmation |
Same(&f.Email) | The same as another field |
Different(&f.Username) | Different from another field |
Alpha | Letters only, from any language, such as José |
AlphaNum | Letters from any language, and numbers |
AlphaDash | Letters from any language, numbers, dashes, and underscores |
ASCII | ASCII characters only. Add it to AlphaDash for a username such as jane_doe |
Lowercase | Already lowercase |
Uppercase | Already uppercase |
StartsWith("+1", "+44") | Starts with one of the prefixes |
EndsWith(".jpg", ".png") | Ends with one of the suffixes |
DoesntStartWith("_") | Starts with none of the prefixes |
DoesntEndWith(".exe") | Ends with none of the suffixes |
Digits(4) | Exactly 4 digits |
DigitsBetween(4, 6) | Between 4 and 6 digits |
MinDigits(4) | At least 4 digits |
MaxDigits(6) | At most 6 digits |
String | Text, for a field of type any. string fields have this rule already |
Lengths count characters, not bytes, and limits are inclusive.
In and NotIn also take the constants of an enum type, such as rule.In(StatusDraft, StatusPublished). The rules compare each constant as a request would send it, so an int enum without a MarshalText method accepts 0 and 1. If your choices are in a []string, spread the slice into In, as in rule.In(kinds...).
Sizes and numbers
| Rule | Passes when the value is |
|---|---|
Min(1) | At least 1 |
Max(100) | At most 100 |
Between(1, 99) | From 1 to 99, inclusive |
Size(12) | Exactly 12 |
GT(&f.Minimum) | Greater than another field |
GTE(&f.Minimum) | Greater than or equal to another field |
LT(&f.Price) | Less than another field |
LTE(&f.Price) | Less than or equal to another field |
Decimal(2) | A number with exactly 2 decimal places |
DecimalBetween(2, 4) | A number with 2 to 4 decimal places |
MultipleOf(12) | A multiple of 12 |
Numeric, Integer, Boolean | A number, a whole number, or a boolean, for a field of type any or string |
The size rules, Min, Max, Between, Size, and the comparisons, measure a field by its Go type: characters for a string, the value for a number, items for a slice or map, and kilobytes for an upload. So rule.Max(100) on a title allows 100 characters, and on an int it allows up to 100. They accept numbers sent as text, such as a form's "12". For example, this form accepts an order of 1 to 100 items, and an optional rating from 0 to 5:
type StoreOrder struct {
Quantity int `json:"quantity"`
Rating *float64 `json:"rating"`
}
func (f *StoreOrder) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Quantity, rule.Required, rule.Min(1), rule.Max(100)),
rule.Field(&f.Rating, rule.Between(0, 5)),
)
}GT, GTE, LT, and LTE always take a pointer to another field, never a literal number. Use Min, Max, or Between for a fixed limit. A comparison fails when the other field is missing, so add rule.Required to that field if clients must send it:
type PriceRange struct {
Minimum int `json:"minimum"`
Maximum int `json:"maximum"`
}
func (f *PriceRange) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Minimum, rule.Required, rule.Min(0)),
rule.Field(&f.Maximum, rule.Required, rule.GTE(&f.Minimum)),
)
}Decimal places and multiples
Decimal counts the decimal places the user wrote. With rule.Decimal(2), "12.50" passes, while "12", "12.5", and "12.500" fail. MultipleOf divides exactly, without a float's rounding, so rule.MultipleOf(0.01) passes "19.99". Add rule.Min(0) if a price can't be negative:
package products
import (
"go.laravel.com/numeric"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
)
type StoreProduct struct {
Price numeric.Decimal `json:"price"`
Quantity int `json:"quantity"`
}
func (f *StoreProduct) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Price, rule.Required, rule.Decimal(2), rule.Min(0)),
rule.Field(&f.Quantity, rule.Required, rule.MultipleOf(12)),
)
}For money and other exact amounts, declare the field as a numeric.Decimal rather than a float64. Validate reads form text and JSON numbers into a numeric.Decimal without rounding them, and a float64 field receives an approximate value.
Dates and times
| Rule | Passes when the value is |
|---|---|
Date | A real calendar date, such as 2024-02-29 |
DateTime | A timestamp with seconds and a UTC offset, such as 2024-02-29T09:30:00Z |
DateFormat("02/01/2006") | Text in one of the layouts |
Timezone | A time zone name, such as America/Chicago |
After(&f.StartsOn) | After another field's date or time, or after a fixed date.Date or time.Time |
AfterOrEqual(&f.StartsOn) | On or after another field's date or time, or a fixed date.Date or time.Time |
Before(&f.EndsOn) | Before another field's date or time, or before a fixed date.Date or time.Time |
BeforeOrEqual(&f.EndsOn) | On or before another field's date or time, or a fixed date.Date or time.Time |
DateEquals(&f.StartsOn) | The same as another field's date or time, or a fixed date.Date or time.Time |
AfterToday | A date after today |
TodayOrAfter | Today or a later date |
BeforeToday | A date before today |
TodayOrBefore | Today or an earlier date |
An HTML <input type="date"> submits a date such as 2024-02-29. Declare the field as a date.Date from go.laravel.com/date, and Laravel checks that the value is a real calendar date, as the Date rule does. Your handler then receives a typed date:
package bookings
import (
"go.laravel.com/date"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
)
type StoreBooking struct {
StartsOn date.Date `json:"starts_on"`
EndsOn date.Date `json:"ends_on"`
}
func (f *StoreBooking) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.StartsOn, rule.Required, rule.TodayOrAfter),
rule.Field(&f.EndsOn, rule.Required, rule.AfterOrEqual(&f.StartsOn)),
)
}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, from the application's clock, so today may already be tomorrow for a user in another part of the world. A test may move today with the test client's TravelTo.
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 time.LoadLocation when you'd like to show a time in the user's time zone. For example, date.TodayIn(r, loc) returns the current date in that zone. 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 time.Time 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:
type StoreAppointment struct {
StartsAt time.Time `json:"starts_at"`
EndsAt time.Time `json:"ends_at"`
}
func (f *StoreAppointment) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.StartsAt, rule.Required),
rule.Field(&f.EndsAt, rule.Required, rule.After(&f.StartsAt)),
)
}说明
An HTML <input type="datetime-local"> submits a time without an offset, such as 2024-02-29T09:30, so a time.Time field can't read it. Declare the field as a string with rule.DateFormat("2006-01-02T15:04"), and parse it in your handler with time.ParseInLocation and the time zone you choose.
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 DateFormat instead, with the layout you expect, written as for time.Parse, such as 02/01/2006. The text must be a real date in exactly that layout, so 02/01/2006 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:
package profile
import (
"time"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
"go.laravel.com/web"
)
type UpdateProfile struct {
Birthday string `json:"birthday"`
}
func (f *UpdateProfile) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Birthday, rule.Required, rule.DateFormat("02/01/2006")),
)
}
func Update(r *web.Request) *web.Response {
form, err := r.Validate[UpdateProfile]()
if err != nil {
return web.Fail(err)
}
birthday, err := time.Parse("02/01/2006", form.Birthday)
if err != nil {
return web.Fail(err)
}
// Store the birthday...
return web.Back()
}The date comparison rules, such as After and TodayOrAfter, 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
| Rule | Passes when the value is |
|---|---|
Email | An email address |
URL | An http or https URL |
URLSchemes("https", "wss") | A URL with one of the schemes |
UUID | A UUID in its hyphenated form |
UUIDVersion(7) | A UUID of version 7 |
ULID | A ULID |
IP | An IPv4 or IPv6 address |
IPv4 | An IPv4 address |
IPv6 | An IPv6 address |
MACAddress | A MAC address |
HexColor | A color such as #1e90ff |
JSON | JSON text |
Base64 | Padded Base64 text |
Regex("^[A-Z]{3}$") | Text that matches the pattern |
NotRegex("(?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:
type UpdateContact struct {
Email string `json:"email"`
Website string `json:"website"`
Callback string `json:"callback"`
}
func (f *UpdateContact) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Email, rule.Required, rule.Email),
rule.Field(&f.Website, rule.URL),
rule.Field(&f.Callback, rule.URLSchemes("https")),
)
}For an IP address, you may declare the field as a netip.Addr instead of using the IP rule. Laravel checks the value's format as the rule would, and shows the rule's error message when the format is wrong. Your handler then receives the parsed address.
Regular expressions
Patterns use Go's regexp syntax, without / delimiters. A pattern matches anywhere in the text, so anchor it with ^ and $ to match the whole value:
rule.Field(&f.SKU, rule.Required, rule.Regex(`^[A-Z]{3}-[0-9]{4}$`))Go's regexp syntax doesn't support look-around or backreferences.
Presence and acceptance
| Rule | 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 a condition holds, 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 an optional checkbox needs no rule: its bool field is false when the box isn't checked:
package auth
import (
"go.laravel.com/hash"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
)
type Register struct {
Email string `json:"email"`
Password string `json:"password"`
Terms bool `json:"terms"`
Newsletter bool `json:"newsletter"`
}
func (f *Register) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Email, rule.Required, rule.Email),
rule.Field(&f.Password, rule.Required, rule.Min(8), hash.Password, rule.Confirmed),
rule.Field(&f.Terms, rule.Accepted),
)
}Database records
model.Unique checks that no row of a model's table already has the submitted value, such as a slug or email address that's already taken. model.Exists checks that some row of a model's table has the submitted value, such as the ID of a category the user picked:
type StorePost struct {
Slug string `json:"slug"`
CategoryID int64 `json:"category_id"`
TagIDs []int64 `json:"tag_ids"`
}
func (f *StorePost) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Slug, rule.Required, rule.Max(255), model.Unique[models.Post]()),
rule.Field(&f.CategoryID, rule.Required, model.Exists[models.Category]()),
rule.Field(&f.TagIDs, rule.Max(20), rule.Each(model.Exists[models.Tag]())),
)
}When you omit the column name, model.Unique checks the column matching the validated field's name (slug for Slug), and model.Exists checks the model's ID column (id). If the form field and column have different names, pass the column name explicitly:
rule.Field(&f.NewEmail, rule.Required, rule.Email, model.Unique[models.User]("email")),
rule.Field(&f.CategorySlug, rule.Required, model.Exists[models.Category]("slug")),Both rules check column names against the model's struct fields, so a misspelled column panics right away.
For a table without a model, pass the table name and column name to rule.Unique or rule.Exists:
rule.Field(&f.Slug, rule.Required, rule.Max(255), rule.Unique("posts", "slug")),
rule.Field(&f.CategoryID, rule.Required, rule.Exists("categories", "id")),Both pairs of rules query the request's database, inside the request's transaction when it has one. When they fail, the user sees messages such as "The slug has already been taken." and "The selected category id is invalid."
Each rule checks one value. To check each ID in a list, put model.Exists inside rule.Each, as TagIDs does in this example. That runs one query per item, so limit how many items the list may hold with rule.Max.
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 whose casing you want to normalize before validation and storage, such as email addresses, add transform:"lowercase" as Transforming input fields describes. When you want to keep the user's original casing (such as a username or display name) while still rejecting case-insensitive duplicates across every database, call IgnoreCase() on model.Unique or rule.Unique:
rule.Field(&f.Username, rule.Required, model.Unique[models.User]().IgnoreCase())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. Use Ignore to skip a given model or ID from the check. In this example, the route runs behind the auth.Authenticate middleware, so Rules reads the logged-in user from the request and ignores their row:
package profile
import (
"go.laravel.com/model"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
"go.laravel.com/web"
"app/models"
)
type UpdateEmail struct {
Email string `json:"email"`
}
func (f *UpdateEmail) Rules(r *web.Request) (validation.Rules, error) {
user := r.User[models.User]()
return validation.For(f,
rule.Field(&f.Email,
rule.Required,
rule.Email,
model.Unique[models.User]().Ignore(user),
),
), nil
}model.Unique's Ignore accepts either the model (value or pointer) or its raw ID, and skips the row matching the model's ID column. On rule.Unique, Ignore takes the ID and skips the row whose id column matches. A page that edits another record has the same problem: on PUT /teams/{team}, the team's own row already holds its current name, so pass the team instead, as the RenameTeam form does.
Filtering rows
Sometimes only some rows should count, such as categories that haven't been archived. Where limits a Unique or Exists rule to the rows whose column holds a value, or is null when the value is nil. For example, this rule only accepts categories that aren't archived:
rule.Field(&f.CategoryID,
rule.Required,
model.Exists[models.Category]().Where("archived_at", nil),
)For conditions that Where can't express, WhereGroup takes a function that adds them to a model query (or a *db.Query on rule.Unique and rule.Exists). Laravel puts the conditions in parentheses, so an OrWhere stays inside them. For example, in a Rules method that takes the request, this rule accepts a public category or one the user owns:
user := r.User[models.User]()
categories := model.Exists[models.Category]().WhereGroup(
func(q *model.Builder[models.Category]) *model.Builder[models.Category] {
return q.WhereEq("visibility", "public").OrWhereEq("owner_id", user.ID)
},
)When a condition needs a route parameter, build the rules from the request. Here, an invitation's email must be unique within the team in the route, not across all teams:
package invitations
import (
"go.laravel.com/model"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
"go.laravel.com/web"
"app/models"
)
type StoreInvitation struct {
Email string `json:"email"`
}
func (f *StoreInvitation) Rules(r *web.Request) (validation.Rules, error) {
team, err := r.PathInt("team")
if err != nil {
return validation.Rules{}, err
}
return validation.For(f,
rule.Field(&f.Email,
rule.Required,
rule.Email,
model.Unique[models.Member]().Where("team_id", team),
),
), nil
}
// POST /teams/{team}/invitations
func Store(r *web.Request) *web.Response {
form, err := r.Validate[StoreInvitation]()
if err != nil {
return web.Fail(err)
}
// Send the invitation to form.Email...
return web.Back()
}Passwords
Use rule.Password on forms that accept a new password, such as registration or password reset:
package auth
import (
"go.laravel.com/hash"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
)
type Register struct {
Email string `json:"email"`
Password string `json:"password"`
}
func (f *Register) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Email, rule.Required, rule.Email),
rule.Field(&f.Password, rule.Required, rule.Password, hash.Password, rule.Confirmed),
)
}By default, rule.Password requires at least 8 characters. To configure your application's password requirements in one place, set Password on laravel.Options in bootstrap/app.go:
return laravel.Options{
// ...
Password: rule.Password.Min(8).Letters().MixedCase().Numbers(),
}| Method | Requires |
|---|---|
Min(8) | At least 8 characters |
Max(64) | At most 64 characters |
Letters() | At least one letter |
MixedCase() | At least one uppercase and one lowercase letter |
Numbers() | At least one number |
Symbols() | At least one symbol, punctuation character, or space |
If a specific form needs different requirements than your application defaults, such as an admin password requiring 12 characters and a symbol, chain those methods directly onto rule.Password on that field:
rule.Field(&f.Password, rule.Required, rule.Password.Min(12).Symbols(), hash.Password, rule.Confirmed)A password that misses more than one requirement reports a message for each one. Call Message to replace them with a single message.
Current password
auth.CurrentPassword checks that the field matches the logged-in user's password. Use it on forms that change a user's password or email address:
package profile
import (
"go.laravel.com/auth"
"go.laravel.com/hash"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
)
type UpdatePassword struct {
CurrentPassword string `json:"current_password"`
Password string `json:"password"`
}
func (f *UpdatePassword) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.CurrentPassword, rule.Required, auth.CurrentPassword),
rule.Field(&f.Password, rule.Required, rule.Min(8), hash.Password, rule.Confirmed),
)
}The rule fails with "The password is incorrect." for a wrong password and for a guest. It reads the user from the session or a request guard.
Give every new password the hash.Password rule, as this form does. It keeps the password within the 72 bytes that bcrypt hashes.
Files
To validate an uploaded file, declare it as a *web.Upload field and give the field the file's rules. Your handler then receives the file in the validated struct, so it may store the file. For example, say your User model has an avatar_path column:
package profile
import (
"go.laravel.com/db"
"go.laravel.com/model"
"go.laravel.com/storage"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
"go.laravel.com/web"
"app/models"
)
type UpdateProfile struct {
Name string `json:"name"`
Avatar *web.Upload `json:"avatar"`
Resume *web.Upload `json:"resume"`
}
func (f *UpdateProfile) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Name, rule.Required, rule.Max(255)),
rule.Field(&f.Avatar, rule.Required, rule.Image, rule.Max(2048)),
rule.Field(&f.Resume, rule.Mimes("pdf"), rule.Max(10240)),
)
}
func Update(r *web.Request) *web.Response {
form, err := r.Validate[UpdateProfile]()
if err != nil {
return web.Fail(err)
}
path, err := form.Avatar.Store(r, storage.Use("public"), "avatars")
if err != nil {
return web.Fail(err)
}
user := r.User[models.User]()
if err := model.Update(r, user, db.Values{"avatar_path": path}); err != nil {
return web.Fail(err)
}
return web.Back()
}A *web.Upload field is nil when the request sends no file, so the optional Resume field needs no extra rule. For an <input type="file" name="photos[]" multiple>, declare the field as a []*web.Upload. Rules outside rule.Each count the files, and rules inside rule.Each check each file, as in rule.Field(&f.Photos, rule.Max(5), rule.Each(rule.Image, rule.Max(5120))).
| Rule | 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(10) | A file of at least 10 kilobytes |
Max(2048) | A file of at most 2,048 kilobytes |
Image and Mimes check the file's contents, not the name the user gave it or the type the browser claims, so a renamed executable fails Image. SVG fails Image, because an SVG can carry scripts.
Extensions 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. Pair Extensions with Mimes when the format matters.
By default, a request may be up to 16 MiB and upload at most 20 files, and Laravel rejects a larger form before validation reads it. To accept larger files on a route, check out the routing guide's section on request limits.
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. Because Validate binds the request into your struct before calling Rules, pass any Go condition to rule.When:
type StoreShipment struct {
Delivery string `json:"delivery"`
Address string `json:"address"`
PickupNotes string `json:"pickup_notes"`
}
func (f *StoreShipment) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Delivery, rule.Required, rule.In("ship", "pickup")),
rule.Field(&f.Address, rule.When(f.Delivery == "ship", rule.Required)),
rule.Field(&f.PickupNotes, rule.When(f.Delivery == "ship", rule.Prohibited)),
)
}rule.When applies its rules only when the condition is true, and skips them when it's false. You may pass several rules to rule.When, including rule.Bail or rule.Each, and write any Go expression for the condition.
Because r.Bind decodes form checkboxes ("on", "yes", "1") and JSON booleans into bool fields, you may check a checkbox field directly, as in rule.When(f.Gift, rule.Required). To check whether a field was sent at all, declare it as validation.Sometimes and check f.Email.Present. To check a field inside an optional nested struct pointer, guard against nil first:
rule.Field(&f.Phone,
rule.When(f.Billing != nil && f.Billing.Country == "US", rule.Required),
)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 struct.
To validate a nested object, declare it as its own struct and give that struct a Rules method of its own. Laravel checks every Address inside a validated form with those rules alongside the form's own Rules method:
type Checkout struct {
Email string `json:"email"`
Shipping Address `json:"shipping"`
Billing *Address `json:"billing"`
}
func (c *Checkout) Rules() validation.Rules {
return validation.For(c,
rule.Field(&c.Email, rule.Required, rule.Email),
)
}
type Address struct {
Street string `json:"street"`
City string `json:"city"`
Country string `json:"country"`
State string `json:"state"`
}
func (a *Address) Rules() validation.Rules {
return validation.For(a,
rule.Field(&a.Street, rule.Required, rule.Max(255)),
rule.Field(&a.City, rule.Required),
rule.Field(&a.Country, rule.Required, rule.Size(2)),
rule.Field(&a.State, rule.When(a.Country == "US", rule.Required)),
)
}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. Laravel runs Address's Rules method on each bound address, so a.Country == "US" checks that address's own country. Billing is a pointer, 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.
Validating lists
Many forms send lists, such as the items in an order or the tags on a post. A slice of a struct with its own Rules method, such as []OrderItem, validates every item with those rules. For a list of text, numbers, or other single values, put the rules for each item inside rule.Each:
type StoreOrder struct {
Items []OrderItem `json:"items"`
Tags []string `json:"tags"`
}
func (f *StoreOrder) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Items, rule.Required, rule.Max(50)),
rule.Field(&f.Tags,
rule.Max(10),
rule.Each(rule.Required, rule.Max(50), rule.Distinct),
),
)
}
type OrderItem struct {
ProductID int64 `json:"product_id"`
Quantity int `json:"quantity"`
Price float64 `json:"price"`
Cost float64 `json:"cost"`
}
func (i *OrderItem) Rules() validation.Rules {
return validation.For(i,
rule.Field(&i.ProductID, rule.Required, model.Exists[models.Product]()),
rule.Field(&i.Quantity, rule.Required, rule.Between(1, 99)),
rule.Field(&i.Price, rule.GT(&i.Cost)),
)
}Rules outside rule.Each apply to the list itself, so rule.Max(10) limits how many tags it holds, and rule.Required would reject 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[]=go or items[0][quantity]=2, and JSON clients send arrays.
GT(&i.Cost) in OrderItem's rules compares each item's price with that item's own cost.
| Rule | Passes when the list |
|---|---|
Min(1) | Has at least 1 item |
Max(10) | Has at most 10 items |
Distinct | Has no duplicate items, when used inside rule.Each |
Contains("editor") | Includes every one of the listed values |
DoesntContain("admin") | Includes none of the listed values |
List | Has keys 0, 1, 2, and so on, in order |
AllowedKeys("theme", "locale") | Is a map whose keys are all among these |
RequiredKeys("theme") | Is a map that has every one of these keys |
For example, a user's preferences might arrive as a map of settings. You don't want to store keys your application doesn't know about, and every user needs a theme. AllowedKeys rejects keys you don't expect, and RequiredKeys requires some keys to exist:
type UpdatePreferences struct {
Preferences map[string]string `json:"preferences"`
}
func (f *UpdatePreferences) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Preferences,
rule.Required,
rule.AllowedKeys("theme", "locale"),
rule.RequiredKeys("theme"),
),
)
}{"preferences": {"theme": "dark"}} passes. An admin key fails AllowedKeys, and sending only locale fails RequiredKeys. To validate each value in a map, use rule.Each on the map field, as you would for a slice.
Contains and distinct
Contains, DoesntContain, and Distinct compare items exactly. Text is case-sensitive, and 1 and "1" are different, so rule.Contains("1") doesn't pass the JSON number 1. Distinct reports every item that repeats another, so ["member", "owner", "member"] gets an error under roles.0 and roles.2:
type UpdateRoles struct {
Roles []string `json:"roles"`
}
func (f *UpdateRoles) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Roles,
rule.Required,
rule.Contains("member"),
rule.DoesntContain("owner"),
rule.Each(rule.Distinct),
),
)
}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", chain Label onto rule.Field. To replace a rule's message, chain Message onto the rule itself:
type StoreUser struct {
Email string `json:"email"`
}
func (f *StoreUser) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Email,
rule.Required.Message("Please enter your :attribute."),
rule.Email,
).Label("email address"),
)
}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 StartsOn has Label("arrival date") and EndsOn has Label("departure date"), the After(&f.StartsOn) rule on EndsOn fails with "The departure date field must be a date after arrival date."
For a list validated with rule.Each, chain Label onto rule.Each and Message onto each item's rules:
type StoreArticle struct {
Tags []string `json:"tags"`
}
func (f *StoreArticle) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Tags,
rule.Max(10).Message("Choose at most :max tags."),
rule.Each(
rule.Required.Message("Tag #:position can't be blank."),
rule.Distinct.Message("Tag #:position is listed twice."),
).Label("tag"),
),
)
}Messages may use these placeholders:
| Placeholder | Value |
|---|---|
:attribute | The field's label |
:Attribute, :ATTRIBUTE | The label with its first letter capitalized, or in capitals |
:min, :max, :size, :value, :digits, :decimal | The rule's limit |
:other, :date | The label of the field that a rule compares with |
:values | The values that a rule compares with |
:format | The layout of DateFormat |
:unexpected | The keys that AllowedKeys rejected |
: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, an int field rejects "two" and a date.Date field rejects text that isn't a valid date. To replace the message for that check, chain Invalid onto rule.Field (or rule.Each for list items):
type StoreTickets struct {
Quantity int `json:"quantity"`
}
func (f *StoreTickets) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Quantity).Invalid("Enter a whole number of tickets."),
)
}Invalid only replaces the message for a value that doesn't fit the field's type. Failures of the rules you give the field, such as Required or Max, keep their own messages.
Custom rules
When the built-in rules don't cover a check, write your own. A rule is any type with a Validate(ctx context.Context, field validation.Field) error method. Return nil to accept the value, or field.Fail with a message to reject it. Then add the rule to a form's rules as you would a built-in rule. You don't register it anywhere:
package rules
import (
"context"
"strings"
"go.laravel.com/validation"
)
type Slug struct{}
func (Slug) Validate(ctx context.Context, field validation.Field) error {
slug := field.String()
if slug == "" || strings.Trim(slug, "abcdefghijklmnopqrstuvwxyz0123456789-") != "" {
return field.Fail("The :attribute field must be a slug.")
}
return nil
}rule.Field(&f.Slug, rule.Required, rule.Max(100), rules.Slug{})For a check that only one form needs, you may write the check inline instead. rule.Func turns a function into a rule:
rule.Field(&f.Username, rule.Func(func(ctx context.Context, field validation.Field) error {
if field.String() == "admin" {
return field.Fail("The :attribute is reserved.")
}
return nil
}))A validation.Field gives the rule what it needs to check:
Valueis the bound Go value on the struct, avalidation.Filefor an upload, ornilwhen the field is missing ornull. You may also read it withString,Number, orFilewhen writing a rule that handles several field types.Pathis the field's path, such asitems.7.slug.Other("country")returns another field of the same struct. In a nested struct's rules,Other("country")reads the same address's country. Use "dot" notation to reach into a nested object, as inOther("shipping.country").Input()returns the whole request's input, for reading a field outside the current struct, such as a top-levelcurrencyfrom inside an order item's rules.
Fail's message may use :attribute for the field's label, and :index and :position for an item in a list. To replace a custom rule's message on a particular field, wrap the rule with rule.Message(rules.Slug{}, "Choose a valid :attribute."). To add placeholders of your own, return a *validation.Failure whose Replace fills them in:
return &validation.Failure{
Rule: "slug",
Message: "The :attribute may only hold :allowed.",
Replace: map[string]string{"allowed": "lowercase letters, numbers, and dashes"},
}Like the built-in rules, a custom rule skips a field that's missing, blank, or null. To check those values too, give the rule an Implicit() bool method that returns true.
Querying the database
A rule receives the request's context, so it may query the database or call another service. For example, this rule passes a coupon code that exists and hasn't expired:
package rules
import (
"context"
"go.laravel.com/date"
"go.laravel.com/db"
"go.laravel.com/validation"
)
type ValidCoupon struct{}
func (ValidCoupon) Validate(ctx context.Context, field validation.Field) error {
exists, err := db.Table("coupons").
WhereEq("code", field.String()).
WhereGt("expires_at", date.Now(ctx)).
Exists(ctx)
if err != nil {
return err
}
if !exists {
return field.Fail("The :attribute isn't a valid coupon.")
}
return nil
}db.Table queries the request's database, inside the request's transaction when it has one. Put cheap rules first and add rule.Bail, so input that's already invalid never reaches the query. Return any error other than field.Fail's, such as a failed query, as it is. It stops validation and reaches your error handler, rather than showing up as a field error.
Validating data without a request
To validate data that didn't come from an HTTP request, such as each row of a CSV file imported by a console command, fill your struct and pass a pointer to it to validation.Validate. It reads the struct's fields directly and runs its Rules method, as r.Validate does for a form. Unique and Exists query the database that ctx carries:
package imports
import (
"context"
"go.laravel.com/model"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
"app/models"
)
type ImportedUser struct {
Name string `json:"name"`
Email string `json:"email"`
}
func (f *ImportedUser) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Name, rule.Required, rule.Max(255)),
rule.Field(&f.Email, rule.Required, rule.Email, model.Unique[models.User]()),
)
}
func checkRow(ctx context.Context, row []string) (ImportedUser, validation.Errors, error) {
user := ImportedUser{
Name: row[0],
Email: row[1],
}
failed, err := validation.Validate(ctx, &user)
return user, failed, err
}If a struct doesn't define a Rules method, or you want to check it with one-off rules instead, pass rule.Field arguments directly to validation.Validate:
failed, err := validation.Validate(ctx, &user,
rule.Field(&user.Name, rule.Required, rule.Max(255)),
rule.Field(&user.Email, rule.Required, rule.Email, model.Unique[models.User]()),
)Validate returns the fields that failed, in the order the struct declares them, and an empty list when the row passes. A non-nil err means a rule couldn't complete, such as a failed database query, rather than invalid data. Without request data, zero values such as an empty string, a nil pointer or slice, or a zero time.Time count as missing for rule.Required.
To inspect the failures in a command or background job, loop over failed.All to visit each field and its messages in order, or call failed.Messages to read the messages for a single field:
if err != nil {
return err
}
for field, messages := range failed.All() {
for _, message := range messages {
fmt.Printf("%s: %s\n", field, message)
}
}
emailErrors := failed.Messages("email")If you call validation.Validate inside an HTTP handler, pass r as the context and return any failures with web.InvalidErrors. Laravel redirects a browser back to the form with the errors, or gives an API client a 422 JSON response that lists them:
func Import(r *web.Request) *web.Response {
user := ImportedUser{
Name: "Taylor",
Email: "not-an-email",
}
failed, err := validation.Validate(r, &user)
if err != nil {
return web.Fail(err)
}
if len(failed) > 0 {
return web.InvalidErrors(failed)
}
// Store the user...
return web.RedirectRoute("users.index")
}Testing
The test client's responses have assertions for validation errors. They read the errors from a JSON response or from the session after a redirect:
package feature_test
import (
"testing"
"app/tests"
)
func TestAPostNeedsATitle(t *testing.T) {
client := tests.New(t)
client.PostJSON("/posts", map[string]any{"title": "", "body": "Hello, world."}).
AssertStatus(422).
AssertInvalid("title").
AssertInvalidMessage("title", "is required").
AssertValid("body")
}AssertInvalidMessage checks that one of the field's messages contains the text. AssertValid() with no fields checks that there were no errors at all. For a page with several forms, check a named bag's errors with AssertInvalidIn("login", "email"), AssertInvalidMessageIn, and AssertValidIn.
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:
import "net/url"
client.From("/posts/create").
Post("/posts", url.Values{"title": {""}, "body": {"Hello, world."}}).
AssertRedirectBackWithErrors("title").
AssertSessionHasInput("body", "Hello, world.")To learn more, check out the testing guide's section on redirecting back.