Laravel validation error code

Laravel is a PHP web application framework with expressive, elegant syntax. We’ve already laid the foundation — freeing you to create without sweating the small things.

Version


Validation

  • Introduction
  • Validation Quickstart

    • Defining The Routes
    • Creating The Controller
    • Writing The Validation Logic
    • Displaying The Validation Errors
    • Repopulating Forms
    • A Note On Optional Fields
    • Validation Error Response Format
  • Form Request Validation

    • Creating Form Requests
    • Authorizing Form Requests
    • Customizing The Error Messages
    • Preparing Input For Validation
  • Manually Creating Validators

    • Automatic Redirection
    • Named Error Bags
    • Customizing The Error Messages
    • After Validation Hook
  • Working With Validated Input
  • Working With Error Messages

    • Specifying Custom Messages In Language Files
    • Specifying Attributes In Language Files
    • Specifying Values In Language Files
  • Available Validation Rules
  • Conditionally Adding Rules
  • Validating Arrays

    • Validating Nested Array Input
    • Error Message Indexes & Positions
  • Validating Files
  • Validating Passwords
  • Custom Validation Rules

    • Using Rule Objects
    • Using Closures
    • Implicit Rules

Introduction

Laravel provides several different approaches to validate your application’s incoming data. It is most common to use the validate method available on all incoming HTTP requests. However, we will discuss other approaches to validation as well.

Laravel includes a wide variety of convenient validation rules that you may apply to data, even providing the ability to validate if values are unique in a given database table. We’ll cover each of these validation rules in detail so that you are familiar with all of Laravel’s validation features.

Validation Quickstart

To learn about Laravel’s powerful validation features, let’s look at a complete example of validating a form and displaying the error messages back to the user. By reading this high-level overview, you’ll be able to gain a good general understanding of how to validate incoming request data using Laravel:

Defining The Routes

First, let’s assume we have the following routes defined in our routes/web.php file:

use AppHttpControllersPostController;

Route::get('/post/create', [PostController::class, 'create']);

Route::post('/post', [PostController::class, 'store']);

The GET route will display a form for the user to create a new blog post, while the POST route will store the new blog post in the database.

Creating The Controller

Next, let’s take a look at a simple controller that handles incoming requests to these routes. We’ll leave the store method empty for now:

<?php

namespace AppHttpControllers;

use AppHttpControllersController;

use IlluminateHttpRequest;

class PostController extends Controller

{

/**

* Show the form to create a new blog post.

*

* @return IlluminateViewView

*/

public function create()

{

return view('post.create');

}

/**

* Store a new blog post.

*

* @param IlluminateHttpRequest $request

* @return IlluminateHttpResponse

*/

public function store(Request $request)

{

// Validate and store the blog post...

}

}

Writing The Validation Logic

Now we are ready to fill in our store method with the logic to validate the new blog post. To do this, we will use the validate method provided by the IlluminateHttpRequest object. If the validation rules pass, your code will keep executing normally; however, if validation fails, an IlluminateValidationValidationException exception will be thrown and the proper error response will automatically be sent back to the user.

If validation fails during a traditional HTTP request, a redirect response to the previous URL will be generated. If the incoming request is an XHR request, a JSON response containing the validation error messages will be returned.

To get a better understanding of the validate method, let’s jump back into the store method:

/**

* Store a new blog post.

*

* @param IlluminateHttpRequest $request

* @return IlluminateHttpResponse

*/

public function store(Request $request)

{

$validated = $request->validate([

'title' => 'required|unique:posts|max:255',

'body' => 'required',

]);

// The blog post is valid...

}

As you can see, the validation rules are passed into the validate method. Don’t worry — all available validation rules are documented. Again, if the validation fails, the proper response will automatically be generated. If the validation passes, our controller will continue executing normally.

Alternatively, validation rules may be specified as arrays of rules instead of a single | delimited string:

$validatedData = $request->validate([

'title' => ['required', 'unique:posts', 'max:255'],

'body' => ['required'],

]);

In addition, you may use the validateWithBag method to validate a request and store any error messages within a named error bag:

$validatedData = $request->validateWithBag('post', [

'title' => ['required', 'unique:posts', 'max:255'],

'body' => ['required'],

]);

Stopping On First Validation Failure

Sometimes you may wish to stop running validation rules on an attribute after the first validation failure. To do so, assign the bail rule to the attribute:

$request->validate([

'title' => 'bail|required|unique:posts|max:255',

'body' => 'required',

]);

In this example, if the unique rule on the title attribute fails, the max rule will not be checked. Rules will be validated in the order they are assigned.

A Note On Nested Attributes

If the incoming HTTP request contains «nested» field data, you may specify these fields in your validation rules using «dot» syntax:

$request->validate([

'title' => 'required|unique:posts|max:255',

'author.name' => 'required',

'author.description' => 'required',

]);

On the other hand, if your field name contains a literal period, you can explicitly prevent this from being interpreted as «dot» syntax by escaping the period with a backslash:

$request->validate([

'title' => 'required|unique:posts|max:255',

'v1.0' => 'required',

]);

Displaying The Validation Errors

So, what if the incoming request fields do not pass the given validation rules? As mentioned previously, Laravel will automatically redirect the user back to their previous location. In addition, all of the validation errors and request input will automatically be flashed to the session.

An $errors variable is shared with all of your application’s views by the IlluminateViewMiddlewareShareErrorsFromSession middleware, which is provided by the web middleware group. When this middleware is applied an $errors variable will always be available in your views, allowing you to conveniently assume the $errors variable is always defined and can be safely used. The $errors variable will be an instance of IlluminateSupportMessageBag. For more information on working with this object, check out its documentation.

So, in our example, the user will be redirected to our controller’s create method when validation fails, allowing us to display the error messages in the view:

<!-- /resources/views/post/create.blade.php -->

<h1>Create Post</h1>

@if ($errors->any())

<div class="alert alert-danger">

<ul>

@foreach ($errors->all() as $error)

<li>{{ $error }}</li>

@endforeach

</ul>

</div>

@endif

<!-- Create Post Form -->

Customizing The Error Messages

Laravel’s built-in validation rules each have an error message that is located in your application’s lang/en/validation.php file. Within this file, you will find a translation entry for each validation rule. You are free to change or modify these messages based on the needs of your application.

In addition, you may copy this file to another translation language directory to translate the messages for your application’s language. To learn more about Laravel localization, check out the complete localization documentation.

XHR Requests & Validation

In this example, we used a traditional form to send data to the application. However, many applications receive XHR requests from a JavaScript powered frontend. When using the validate method during an XHR request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.

The @error Directive

You may use the @error Blade directive to quickly determine if validation error messages exist for a given attribute. Within an @error directive, you may echo the $message variable to display the error message:

<!-- /resources/views/post/create.blade.php -->

<label for="title">Post Title</label>

<input id="title"

type="text"

name="title"

class="@error('title') is-invalid @enderror">

@error('title')

<div class="alert alert-danger">{{ $message }}</div>

@enderror

If you are using named error bags, you may pass the name of the error bag as the second argument to the @error directive:

<input ... class="@error('title', 'post') is-invalid @enderror">

Repopulating Forms

When Laravel generates a redirect response due to a validation error, the framework will automatically flash all of the request’s input to the session. This is done so that you may conveniently access the input during the next request and repopulate the form that the user attempted to submit.

To retrieve flashed input from the previous request, invoke the old method on an instance of IlluminateHttpRequest. The old method will pull the previously flashed input data from the session:

$title = $request->old('title');

Laravel also provides a global old helper. If you are displaying old input within a Blade template, it is more convenient to use the old helper to repopulate the form. If no old input exists for the given field, null will be returned:

<input type="text" name="title" value="{{ old('title') }}">

A Note On Optional Fields

By default, Laravel includes the TrimStrings and ConvertEmptyStringsToNull middleware in your application’s global middleware stack. These middleware are listed in the stack by the AppHttpKernel class. Because of this, you will often need to mark your «optional» request fields as nullable if you do not want the validator to consider null values as invalid. For example:

$request->validate([

'title' => 'required|unique:posts|max:255',

'body' => 'required',

'publish_at' => 'nullable|date',

]);

In this example, we are specifying that the publish_at field may be either null or a valid date representation. If the nullable modifier is not added to the rule definition, the validator would consider null an invalid date.

Validation Error Response Format

When your application throws a IlluminateValidationValidationException exception and the incoming HTTP request is expecting a JSON response, Laravel will automatically format the error messages for you and return a 422 Unprocessable Entity HTTP response.

Below, you can review an example of the JSON response format for validation errors. Note that nested error keys are flattened into «dot» notation format:

{

"message": "The team name must be a string. (and 4 more errors)",

"errors": {

"team_name": [

"The team name must be a string.",

"The team name must be at least 1 characters."

],

"authorization.role": [

"The selected authorization.role is invalid."

],

"users.0.email": [

"The users.0.email field is required."

],

"users.2.email": [

"The users.2.email must be a valid email address."

]

}

}

Form Request Validation

Creating Form Requests

For more complex validation scenarios, you may wish to create a «form request». Form requests are custom request classes that encapsulate their own validation and authorization logic. To create a form request class, you may use the make:request Artisan CLI command:

php artisan make:request StorePostRequest

The generated form request class will be placed in the app/Http/Requests directory. If this directory does not exist, it will be created when you run the make:request command. Each form request generated by Laravel has two methods: authorize and rules.

As you might have guessed, the authorize method is responsible for determining if the currently authenticated user can perform the action represented by the request, while the rules method returns the validation rules that should apply to the request’s data:

/**

* Get the validation rules that apply to the request.

*

* @return array

*/

public function rules()

{

return [

'title' => 'required|unique:posts|max:255',

'body' => 'required',

];

}

Note
You may type-hint any dependencies you require within the rules method’s signature. They will automatically be resolved via the Laravel service container.

So, how are the validation rules evaluated? All you need to do is type-hint the request on your controller method. The incoming form request is validated before the controller method is called, meaning you do not need to clutter your controller with any validation logic:

/**

* Store a new blog post.

*

* @param AppHttpRequestsStorePostRequest $request

* @return IlluminateHttpResponse

*/

public function store(StorePostRequest $request)

{

// The incoming request is valid...

// Retrieve the validated input data...

$validated = $request->validated();

// Retrieve a portion of the validated input data...

$validated = $request->safe()->only(['name', 'email']);

$validated = $request->safe()->except(['name', 'email']);

}

If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an XHR request, an HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.

Adding After Hooks To Form Requests

If you would like to add an «after» validation hook to a form request, you may use the withValidator method. This method receives the fully constructed validator, allowing you to call any of its methods before the validation rules are actually evaluated:

/**

* Configure the validator instance.

*

* @param IlluminateValidationValidator $validator

* @return void

*/

public function withValidator($validator)

{

$validator->after(function ($validator) {

if ($this->somethingElseIsInvalid()) {

$validator->errors()->add('field', 'Something is wrong with this field!');

}

});

}

Stopping On First Validation Failure Attribute

By adding a stopOnFirstFailure property to your request class, you may inform the validator that it should stop validating all attributes once a single validation failure has occurred:

/**

* Indicates if the validator should stop on the first rule failure.

*

* @var bool

*/

protected $stopOnFirstFailure = true;

Customizing The Redirect Location

As previously discussed, a redirect response will be generated to send the user back to their previous location when form request validation fails. However, you are free to customize this behavior. To do so, define a $redirect property on your form request:

/**

* The URI that users should be redirected to if validation fails.

*

* @var string

*/

protected $redirect = '/dashboard';

Or, if you would like to redirect users to a named route, you may define a $redirectRoute property instead:

/**

* The route that users should be redirected to if validation fails.

*

* @var string

*/

protected $redirectRoute = 'dashboard';

Authorizing Form Requests

The form request class also contains an authorize method. Within this method, you may determine if the authenticated user actually has the authority to update a given resource. For example, you may determine if a user actually owns a blog comment they are attempting to update. Most likely, you will interact with your authorization gates and policies within this method:

use AppModelsComment;

/**

* Determine if the user is authorized to make this request.

*

* @return bool

*/

public function authorize()

{

$comment = Comment::find($this->route('comment'));

return $comment && $this->user()->can('update', $comment);

}

Since all form requests extend the base Laravel request class, we may use the user method to access the currently authenticated user. Also, note the call to the route method in the example above. This method grants you access to the URI parameters defined on the route being called, such as the {comment} parameter in the example below:

Route::post('/comment/{comment}');

Therefore, if your application is taking advantage of route model binding, your code may be made even more succinct by accessing the resolved model as a property of the request:

return $this->user()->can('update', $this->comment);

If the authorize method returns false, an HTTP response with a 403 status code will automatically be returned and your controller method will not execute.

If you plan to handle authorization logic for the request in another part of your application, you may simply return true from the authorize method:

/**

* Determine if the user is authorized to make this request.

*

* @return bool

*/

public function authorize()

{

return true;

}

Note
You may type-hint any dependencies you need within the authorize method’s signature. They will automatically be resolved via the Laravel service container.

Customizing The Error Messages

You may customize the error messages used by the form request by overriding the messages method. This method should return an array of attribute / rule pairs and their corresponding error messages:

/**

* Get the error messages for the defined validation rules.

*

* @return array

*/

public function messages()

{

return [

'title.required' => 'A title is required',

'body.required' => 'A message is required',

];

}

Customizing The Validation Attributes

Many of Laravel’s built-in validation rule error messages contain an :attribute placeholder. If you would like the :attribute placeholder of your validation message to be replaced with a custom attribute name, you may specify the custom names by overriding the attributes method. This method should return an array of attribute / name pairs:

/**

* Get custom attributes for validator errors.

*

* @return array

*/

public function attributes()

{

return [

'email' => 'email address',

];

}

Preparing Input For Validation

If you need to prepare or sanitize any data from the request before you apply your validation rules, you may use the prepareForValidation method:

use IlluminateSupportStr;

/**

* Prepare the data for validation.

*

* @return void

*/

protected function prepareForValidation()

{

$this->merge([

'slug' => Str::slug($this->slug),

]);

}

Likewise, if you need to normalize any request data after validation is complete, you may use the passedValidation method:

use IlluminateSupportStr;

/**

* Handle a passed validation attempt.

*

* @return void

*/

protected function passedValidation()

{

$this->replace(['name' => 'Taylor']);

}

Manually Creating Validators

If you do not want to use the validate method on the request, you may create a validator instance manually using the Validator facade. The make method on the facade generates a new validator instance:

<?php

namespace AppHttpControllers;

use AppHttpControllersController;

use IlluminateHttpRequest;

use IlluminateSupportFacadesValidator;

class PostController extends Controller

{

/**

* Store a new blog post.

*

* @param Request $request

* @return Response

*/

public function store(Request $request)

{

$validator = Validator::make($request->all(), [

'title' => 'required|unique:posts|max:255',

'body' => 'required',

]);

if ($validator->fails()) {

return redirect('post/create')

->withErrors($validator)

->withInput();

}

// Retrieve the validated input...

$validated = $validator->validated();

// Retrieve a portion of the validated input...

$validated = $validator->safe()->only(['name', 'email']);

$validated = $validator->safe()->except(['name', 'email']);

// Store the blog post...

}

}

The first argument passed to the make method is the data under validation. The second argument is an array of the validation rules that should be applied to the data.

After determining whether the request validation failed, you may use the withErrors method to flash the error messages to the session. When using this method, the $errors variable will automatically be shared with your views after redirection, allowing you to easily display them back to the user. The withErrors method accepts a validator, a MessageBag, or a PHP array.

Stopping On First Validation Failure

The stopOnFirstFailure method will inform the validator that it should stop validating all attributes once a single validation failure has occurred:

if ($validator->stopOnFirstFailure()->fails()) {

// ...

}

Automatic Redirection

If you would like to create a validator instance manually but still take advantage of the automatic redirection offered by the HTTP request’s validate method, you may call the validate method on an existing validator instance. If validation fails, the user will automatically be redirected or, in the case of an XHR request, a JSON response will be returned:

Validator::make($request->all(), [

'title' => 'required|unique:posts|max:255',

'body' => 'required',

])->validate();

You may use the validateWithBag method to store the error messages in a named error bag if validation fails:

Validator::make($request->all(), [

'title' => 'required|unique:posts|max:255',

'body' => 'required',

])->validateWithBag('post');

Named Error Bags

If you have multiple forms on a single page, you may wish to name the MessageBag containing the validation errors, allowing you to retrieve the error messages for a specific form. To achieve this, pass a name as the second argument to withErrors:

return redirect('register')->withErrors($validator, 'login');

You may then access the named MessageBag instance from the $errors variable:

{{ $errors->login->first('email') }}

Customizing The Error Messages

If needed, you may provide custom error messages that a validator instance should use instead of the default error messages provided by Laravel. There are several ways to specify custom messages. First, you may pass the custom messages as the third argument to the Validator::make method:

$validator = Validator::make($input, $rules, $messages = [

'required' => 'The :attribute field is required.',

]);

In this example, the :attribute placeholder will be replaced by the actual name of the field under validation. You may also utilize other placeholders in validation messages. For example:

$messages = [

'same' => 'The :attribute and :other must match.',

'size' => 'The :attribute must be exactly :size.',

'between' => 'The :attribute value :input is not between :min - :max.',

'in' => 'The :attribute must be one of the following types: :values',

];

Specifying A Custom Message For A Given Attribute

Sometimes you may wish to specify a custom error message only for a specific attribute. You may do so using «dot» notation. Specify the attribute’s name first, followed by the rule:

$messages = [

'email.required' => 'We need to know your email address!',

];

Specifying Custom Attribute Values

Many of Laravel’s built-in error messages include an :attribute placeholder that is replaced with the name of the field or attribute under validation. To customize the values used to replace these placeholders for specific fields, you may pass an array of custom attributes as the fourth argument to the Validator::make method:

$validator = Validator::make($input, $rules, $messages, [

'email' => 'email address',

]);

After Validation Hook

You may also attach callbacks to be run after validation is completed. This allows you to easily perform further validation and even add more error messages to the message collection. To get started, call the after method on a validator instance:

$validator = Validator::make(/* ... */);

$validator->after(function ($validator) {

if ($this->somethingElseIsInvalid()) {

$validator->errors()->add(

'field', 'Something is wrong with this field!'

);

}

});

if ($validator->fails()) {

//

}

Working With Validated Input

After validating incoming request data using a form request or a manually created validator instance, you may wish to retrieve the incoming request data that actually underwent validation. This can be accomplished in several ways. First, you may call the validated method on a form request or validator instance. This method returns an array of the data that was validated:

$validated = $request->validated();

$validated = $validator->validated();

Alternatively, you may call the safe method on a form request or validator instance. This method returns an instance of IlluminateSupportValidatedInput. This object exposes only, except, and all methods to retrieve a subset of the validated data or the entire array of validated data:

$validated = $request->safe()->only(['name', 'email']);

$validated = $request->safe()->except(['name', 'email']);

$validated = $request->safe()->all();

In addition, the IlluminateSupportValidatedInput instance may be iterated over and accessed like an array:

// Validated data may be iterated...

foreach ($request->safe() as $key => $value) {

//

}

// Validated data may be accessed as an array...

$validated = $request->safe();

$email = $validated['email'];

If you would like to add additional fields to the validated data, you may call the merge method:

$validated = $request->safe()->merge(['name' => 'Taylor Otwell']);

If you would like to retrieve the validated data as a collection instance, you may call the collect method:

$collection = $request->safe()->collect();

Working With Error Messages

After calling the errors method on a Validator instance, you will receive an IlluminateSupportMessageBag instance, which has a variety of convenient methods for working with error messages. The $errors variable that is automatically made available to all views is also an instance of the MessageBag class.

Retrieving The First Error Message For A Field

To retrieve the first error message for a given field, use the first method:

$errors = $validator->errors();

echo $errors->first('email');

Retrieving All Error Messages For A Field

If you need to retrieve an array of all the messages for a given field, use the get method:

foreach ($errors->get('email') as $message) {

//

}

If you are validating an array form field, you may retrieve all of the messages for each of the array elements using the * character:

foreach ($errors->get('attachments.*') as $message) {

//

}

Retrieving All Error Messages For All Fields

To retrieve an array of all messages for all fields, use the all method:

foreach ($errors->all() as $message) {

//

}

Determining If Messages Exist For A Field

The has method may be used to determine if any error messages exist for a given field:

if ($errors->has('email')) {

//

}

Specifying Custom Messages In Language Files

Laravel’s built-in validation rules each have an error message that is located in your application’s lang/en/validation.php file. Within this file, you will find a translation entry for each validation rule. You are free to change or modify these messages based on the needs of your application.

In addition, you may copy this file to another translation language directory to translate the messages for your application’s language. To learn more about Laravel localization, check out the complete localization documentation.

Custom Messages For Specific Attributes

You may customize the error messages used for specified attribute and rule combinations within your application’s validation language files. To do so, add your message customizations to the custom array of your application’s lang/xx/validation.php language file:

'custom' => [

'email' => [

'required' => 'We need to know your email address!',

'max' => 'Your email address is too long!'

],

],

Specifying Attributes In Language Files

Many of Laravel’s built-in error messages include an :attribute placeholder that is replaced with the name of the field or attribute under validation. If you would like the :attribute portion of your validation message to be replaced with a custom value, you may specify the custom attribute name in the attributes array of your lang/xx/validation.php language file:

'attributes' => [

'email' => 'email address',

],

Specifying Values In Language Files

Some of Laravel’s built-in validation rule error messages contain a :value placeholder that is replaced with the current value of the request attribute. However, you may occasionally need the :value portion of your validation message to be replaced with a custom representation of the value. For example, consider the following rule that specifies that a credit card number is required if the payment_type has a value of cc:

Validator::make($request->all(), [

'credit_card_number' => 'required_if:payment_type,cc'

]);

If this validation rule fails, it will produce the following error message:

The credit card number field is required when payment type is cc.

Instead of displaying cc as the payment type value, you may specify a more user-friendly value representation in your lang/xx/validation.php language file by defining a values array:

'values' => [

'payment_type' => [

'cc' => 'credit card'

],

],

After defining this value, the validation rule will produce the following error message:

The credit card number field is required when payment type is credit card.

Available Validation Rules

Below is a list of all available validation rules and their function:

accepted

The field under validation must be "yes", "on", 1, or true. This is useful for validating «Terms of Service» acceptance or similar fields.

accepted_if:anotherfield,value,…

The field under validation must be "yes", "on", 1, or true if another field under validation is equal to a specified value. This is useful for validating «Terms of Service» acceptance or similar fields.

active_url

The field under validation must have a valid A or AAAA record according to the dns_get_record PHP function. The hostname of the provided URL is extracted using the parse_url PHP function before being passed to dns_get_record.

after:date

The field under validation must be a value after a given date. The dates will be passed into the strtotime PHP function in order to be converted to a valid DateTime instance:

'start_date' => 'required|date|after:tomorrow'

Instead of passing a date string to be evaluated by strtotime, you may specify another field to compare against the date:

'finish_date' => 'required|date|after:start_date'

after_or_equal:date

The field under validation must be a value after or equal to the given date. For more information, see the after rule.

alpha

The field under validation must be entirely Unicode alphabetic characters contained in p{L} and p{M}.

To restrict this validation rule to characters in the ASCII range (a-z and A-Z), you may provide the ascii option to the validation rule:

'username' => 'alpha:ascii',

alpha_dash

The field under validation must be entirely Unicode alpha-numeric characters contained in p{L}, p{M}, p{N}, as well as ASCII dashes (-) and ASCII underscores (_).

To restrict this validation rule to characters in the ASCII range (a-z and A-Z), you may provide the ascii option to the validation rule:

'username' => 'alpha_dash:ascii',

alpha_num

The field under validation must be entirely Unicode alpha-numeric characters contained in p{L}, p{M}, and p{N}.

To restrict this validation rule to characters in the ASCII range (a-z and A-Z), you may provide the ascii option to the validation rule:

'username' => 'alpha_num:ascii',

array

The field under validation must be a PHP array.

When additional values are provided to the array rule, each key in the input array must be present within the list of values provided to the rule. In the following example, the admin key in the input array is invalid since it is not contained in the list of values provided to the array rule:

use IlluminateSupportFacadesValidator;

$input = [

'user' => [

'name' => 'Taylor Otwell',

'username' => 'taylorotwell',

'admin' => true,

],

];

Validator::make($input, [

'user' => 'array:name,username',

]);

In general, you should always specify the array keys that are allowed to be present within your array.

ascii

The field under validation must be entirely 7-bit ASCII characters.

bail

Stop running validation rules for the field after the first validation failure.

While the bail rule will only stop validating a specific field when it encounters a validation failure, the stopOnFirstFailure method will inform the validator that it should stop validating all attributes once a single validation failure has occurred:

if ($validator->stopOnFirstFailure()->fails()) {

// ...

}

before:date

The field under validation must be a value preceding the given date. The dates will be passed into the PHP strtotime function in order to be converted into a valid DateTime instance. In addition, like the after rule, the name of another field under validation may be supplied as the value of date.

before_or_equal:date

The field under validation must be a value preceding or equal to the given date. The dates will be passed into the PHP strtotime function in order to be converted into a valid DateTime instance. In addition, like the after rule, the name of another field under validation may be supplied as the value of date.

between:min,max

The field under validation must have a size between the given min and max (inclusive). Strings, numerics, arrays, and files are evaluated in the same fashion as the size rule.

boolean

The field under validation must be able to be cast as a boolean. Accepted input are true, false, 1, 0, "1", and "0".

confirmed

The field under validation must have a matching field of {field}_confirmation. For example, if the field under validation is password, a matching password_confirmation field must be present in the input.

current_password

The field under validation must match the authenticated user’s password. You may specify an authentication guard using the rule’s first parameter:

'password' => 'current_password:api'

date

The field under validation must be a valid, non-relative date according to the strtotime PHP function.

date_equals:date

The field under validation must be equal to the given date. The dates will be passed into the PHP strtotime function in order to be converted into a valid DateTime instance.

date_format:format,…

The field under validation must match one of the given formats. You should use either date or date_format when validating a field, not both. This validation rule supports all formats supported by PHP’s DateTime class.

decimal:min,max

The field under validation must be numeric and must contain the specified number of decimal places:

// Must have exactly two decimal places (9.99)...

'price' => 'decimal:2'

// Must have between 2 and 4 decimal places...

'price' => 'decimal:2,4'

declined

The field under validation must be "no", "off", 0, or false.

declined_if:anotherfield,value,…

The field under validation must be "no", "off", 0, or false if another field under validation is equal to a specified value.

different:field

The field under validation must have a different value than field.

digits:value

The integer under validation must have an exact length of value.

digits_between:min,max

The integer validation must have a length between the given min and max.

dimensions

The file under validation must be an image meeting the dimension constraints as specified by the rule’s parameters:

'avatar' => 'dimensions:min_width=100,min_height=200'

Available constraints are: min_width, max_width, min_height, max_height, width, height, ratio.

A ratio constraint should be represented as width divided by height. This can be specified either by a fraction like 3/2 or a float like 1.5:

'avatar' => 'dimensions:ratio=3/2'

Since this rule requires several arguments, you may use the Rule::dimensions method to fluently construct the rule:

use IlluminateSupportFacadesValidator;

use IlluminateValidationRule;

Validator::make($data, [

'avatar' => [

'required',

Rule::dimensions()->maxWidth(1000)->maxHeight(500)->ratio(3 / 2),

],

]);

distinct

When validating arrays, the field under validation must not have any duplicate values:

'foo.*.id' => 'distinct'

Distinct uses loose variable comparisons by default. To use strict comparisons, you may add the strict parameter to your validation rule definition:

'foo.*.id' => 'distinct:strict'

You may add ignore_case to the validation rule’s arguments to make the rule ignore capitalization differences:

'foo.*.id' => 'distinct:ignore_case'

doesnt_start_with:foo,bar,…

The field under validation must not start with one of the given values.

doesnt_end_with:foo,bar,…

The field under validation must not end with one of the given values.

email

The field under validation must be formatted as an email address. This validation rule utilizes the egulias/email-validator package for validating the email address. By default, the RFCValidation validator is applied, but you can apply other validation styles as well:

'email' => 'email:rfc,dns'

The example above will apply the RFCValidation and DNSCheckValidation validations. Here’s a full list of validation styles you can apply:

  • rfc: RFCValidation
  • strict: NoRFCWarningsValidation
  • dns: DNSCheckValidation
  • spoof: SpoofCheckValidation
  • filter: FilterEmailValidation
  • filter_unicode: FilterEmailValidation::unicode()

The filter validator, which uses PHP’s filter_var function, ships with Laravel and was Laravel’s default email validation behavior prior to Laravel version 5.8.

Warning
The dns and spoof validators require the PHP intl extension.

ends_with:foo,bar,…

The field under validation must end with one of the given values.

enum

The Enum rule is a class based rule that validates whether the field under validation contains a valid enum value. The Enum rule accepts the name of the enum as its only constructor argument:

use AppEnumsServerStatus;

use IlluminateValidationRulesEnum;

$request->validate([

'status' => [new Enum(ServerStatus::class)],

]);

Warning
Enums are only available on PHP 8.1+.

exclude

The field under validation will be excluded from the request data returned by the validate and validated methods.

exclude_if:anotherfield,value

The field under validation will be excluded from the request data returned by the validate and validated methods if the anotherfield field is equal to value.

If complex conditional exclusion logic is required, you may utilize the Rule::excludeIf method. This method accepts a boolean or a closure. When given a closure, the closure should return true or false to indicate if the field under validation should be excluded:

use IlluminateSupportFacadesValidator;

use IlluminateValidationRule;

Validator::make($request->all(), [

'role_id' => Rule::excludeIf($request->user()->is_admin),

]);

Validator::make($request->all(), [

'role_id' => Rule::excludeIf(fn () => $request->user()->is_admin),

]);

exclude_unless:anotherfield,value

The field under validation will be excluded from the request data returned by the validate and validated methods unless anotherfield‘s field is equal to value. If value is null (exclude_unless:name,null), the field under validation will be excluded unless the comparison field is null or the comparison field is missing from the request data.

exclude_with:anotherfield

The field under validation will be excluded from the request data returned by the validate and validated methods if the anotherfield field is present.

exclude_without:anotherfield

The field under validation will be excluded from the request data returned by the validate and validated methods if the anotherfield field is not present.

exists:table,column

The field under validation must exist in a given database table.

Basic Usage Of Exists Rule

'state' => 'exists:states'

If the column option is not specified, the field name will be used. So, in this case, the rule will validate that the states database table contains a record with a state column value matching the request’s state attribute value.

Specifying A Custom Column Name

You may explicitly specify the database column name that should be used by the validation rule by placing it after the database table name:

'state' => 'exists:states,abbreviation'

Occasionally, you may need to specify a specific database connection to be used for the exists query. You can accomplish this by prepending the connection name to the table name:

'email' => 'exists:connection.staff,email'

Instead of specifying the table name directly, you may specify the Eloquent model which should be used to determine the table name:

'user_id' => 'exists:AppModelsUser,id'

If you would like to customize the query executed by the validation rule, you may use the Rule class to fluently define the rule. In this example, we’ll also specify the validation rules as an array instead of using the | character to delimit them:

use IlluminateSupportFacadesValidator;

use IlluminateValidationRule;

Validator::make($data, [

'email' => [

'required',

Rule::exists('staff')->where(function ($query) {

return $query->where('account_id', 1);

}),

],

]);

You may explicitly specify the database column name that should be used by the exists rule generated by the Rule::exists method by providing the column name as the second argument to the exists method:

'state' => Rule::exists('states', 'abbreviation'),

file

The field under validation must be a successfully uploaded file.

filled

The field under validation must not be empty when it is present.

gt:field

The field under validation must be greater than the given field. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the size rule.

gte:field

The field under validation must be greater than or equal to the given field. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the size rule.

image

The file under validation must be an image (jpg, jpeg, png, bmp, gif, svg, or webp).

in:foo,bar,…

The field under validation must be included in the given list of values. Since this rule often requires you to implode an array, the Rule::in method may be used to fluently construct the rule:

use IlluminateSupportFacadesValidator;

use IlluminateValidationRule;

Validator::make($data, [

'zones' => [

'required',

Rule::in(['first-zone', 'second-zone']),

],

]);

When the in rule is combined with the array rule, each value in the input array must be present within the list of values provided to the in rule. In the following example, the LAS airport code in the input array is invalid since it is not contained in the list of airports provided to the in rule:

use IlluminateSupportFacadesValidator;

use IlluminateValidationRule;

$input = [

'airports' => ['NYC', 'LAS'],

];

Validator::make($input, [

'airports' => [

'required',

'array',

],

'airports.*' => Rule::in(['NYC', 'LIT']),

]);

in_array:anotherfield.*

The field under validation must exist in anotherfield‘s values.

integer

The field under validation must be an integer.

Warning
This validation rule does not verify that the input is of the «integer» variable type, only that the input is of a type accepted by PHP’s FILTER_VALIDATE_INT rule. If you need to validate the input as being a number please use this rule in combination with the numeric validation rule.

ip

The field under validation must be an IP address.

ipv4

The field under validation must be an IPv4 address.

ipv6

The field under validation must be an IPv6 address.

json

The field under validation must be a valid JSON string.

lt:field

The field under validation must be less than the given field. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the size rule.

lte:field

The field under validation must be less than or equal to the given field. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the size rule.

lowercase

The field under validation must be lowercase.

mac_address

The field under validation must be a MAC address.

max:value

The field under validation must be less than or equal to a maximum value. Strings, numerics, arrays, and files are evaluated in the same fashion as the size rule.

max_digits:value

The integer under validation must have a maximum length of value.

mimetypes:text/plain,…

The file under validation must match one of the given MIME types:

'video' => 'mimetypes:video/avi,video/mpeg,video/quicktime'

To determine the MIME type of the uploaded file, the file’s contents will be read and the framework will attempt to guess the MIME type, which may be different from the client’s provided MIME type.

mimes:foo,bar,…

The file under validation must have a MIME type corresponding to one of the listed extensions.

Basic Usage Of MIME Rule

'photo' => 'mimes:jpg,bmp,png'

Even though you only need to specify the extensions, this rule actually validates the MIME type of the file by reading the file’s contents and guessing its MIME type. A full listing of MIME types and their corresponding extensions may be found at the following location:

https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types

min:value

The field under validation must have a minimum value. Strings, numerics, arrays, and files are evaluated in the same fashion as the size rule.

min_digits:value

The integer under validation must have a minimum length of value.

multiple_of:value

The field under validation must be a multiple of value.

missing

The field under validation must not be present in the input data.

missing_if:anotherfield,value,…

The field under validation must not be present if the anotherfield field is equal to any value.

missing_unless:anotherfield,value

The field under validation must not be present unless the anotherfield field is equal to any value.

missing_with:foo,bar,…

The field under validation must not be present only if any of the other specified fields are present.

missing_with_all:foo,bar,…

The field under validation must not be present only if all of the other specified fields are present.

not_in:foo,bar,…

The field under validation must not be included in the given list of values. The Rule::notIn method may be used to fluently construct the rule:

use IlluminateValidationRule;

Validator::make($data, [

'toppings' => [

'required',

Rule::notIn(['sprinkles', 'cherries']),

],

]);

not_regex:pattern

The field under validation must not match the given regular expression.

Internally, this rule uses the PHP preg_match function. The pattern specified should obey the same formatting required by preg_match and thus also include valid delimiters. For example: 'email' => 'not_regex:/^.+$/i'.

Warning
When using the regex / not_regex patterns, it may be necessary to specify your validation rules using an array instead of using | delimiters, especially if the regular expression contains a | character.

nullable

The field under validation may be null.

numeric

The field under validation must be numeric.

password

The field under validation must match the authenticated user’s password.

Warning
This rule was renamed to current_password with the intention of removing it in Laravel 9. Please use the Current Password rule instead.

present

The field under validation must exist in the input data.

prohibited

The field under validation must be missing or empty. A field is «empty» if it meets one of the following criteria:

  • The value is null.
  • The value is an empty string.
  • The value is an empty array or empty Countable object.
  • The value is an uploaded file with an empty path.

prohibited_if:anotherfield,value,…

The field under validation must be missing or empty if the anotherfield field is equal to any value. A field is «empty» if it meets one of the following criteria:

  • The value is null.
  • The value is an empty string.
  • The value is an empty array or empty Countable object.
  • The value is an uploaded file with an empty path.

If complex conditional prohibition logic is required, you may utilize the Rule::prohibitedIf method. This method accepts a boolean or a closure. When given a closure, the closure should return true or false to indicate if the field under validation should be prohibited:

use IlluminateSupportFacadesValidator;

use IlluminateValidationRule;

Validator::make($request->all(), [

'role_id' => Rule::prohibitedIf($request->user()->is_admin),

]);

Validator::make($request->all(), [

'role_id' => Rule::prohibitedIf(fn () => $request->user()->is_admin),

]);

prohibited_unless:anotherfield,value,…

The field under validation must be missing or empty unless the anotherfield field is equal to any value. A field is «empty» if it meets one of the following criteria:

  • The value is null.
  • The value is an empty string.
  • The value is an empty array or empty Countable object.
  • The value is an uploaded file with an empty path.

prohibits:anotherfield,…

If the field under validation is not missing or empty, all fields in anotherfield must be missing or empty. A field is «empty» if it meets one of the following criteria:

  • The value is null.
  • The value is an empty string.
  • The value is an empty array or empty Countable object.
  • The value is an uploaded file with an empty path.

regex:pattern

The field under validation must match the given regular expression.

Internally, this rule uses the PHP preg_match function. The pattern specified should obey the same formatting required by preg_match and thus also include valid delimiters. For example: 'email' => 'regex:/^[email protected]+$/i'.

Warning
When using the regex / not_regex patterns, it may be necessary to specify rules in an array instead of using | delimiters, especially if the regular expression contains a | character.

required

The field under validation must be present in the input data and not empty. A field is «empty» if it meets one of the following criteria:

  • The value is null.
  • The value is an empty string.
  • The value is an empty array or empty Countable object.
  • The value is an uploaded file with no path.

required_if:anotherfield,value,…

The field under validation must be present and not empty if the anotherfield field is equal to any value.

If you would like to construct a more complex condition for the required_if rule, you may use the Rule::requiredIf method. This method accepts a boolean or a closure. When passed a closure, the closure should return true or false to indicate if the field under validation is required:

use IlluminateSupportFacadesValidator;

use IlluminateValidationRule;

Validator::make($request->all(), [

'role_id' => Rule::requiredIf($request->user()->is_admin),

]);

Validator::make($request->all(), [

'role_id' => Rule::requiredIf(fn () => $request->user()->is_admin),

]);

required_unless:anotherfield,value,…

The field under validation must be present and not empty unless the anotherfield field is equal to any value. This also means anotherfield must be present in the request data unless value is null. If value is null (required_unless:name,null), the field under validation will be required unless the comparison field is null or the comparison field is missing from the request data.

required_with:foo,bar,…

The field under validation must be present and not empty only if any of the other specified fields are present and not empty.

required_with_all:foo,bar,…

The field under validation must be present and not empty only if all of the other specified fields are present and not empty.

required_without:foo,bar,…

The field under validation must be present and not empty only when any of the other specified fields are empty or not present.

required_without_all:foo,bar,…

The field under validation must be present and not empty only when all of the other specified fields are empty or not present.

required_array_keys:foo,bar,…

The field under validation must be an array and must contain at least the specified keys.

same:field

The given field must match the field under validation.

size:value

The field under validation must have a size matching the given value. For string data, value corresponds to the number of characters. For numeric data, value corresponds to a given integer value (the attribute must also have the numeric or integer rule). For an array, size corresponds to the count of the array. For files, size corresponds to the file size in kilobytes. Let’s look at some examples:

// Validate that a string is exactly 12 characters long...

'title' => 'size:12';

// Validate that a provided integer equals 10...

'seats' => 'integer|size:10';

// Validate that an array has exactly 5 elements...

'tags' => 'array|size:5';

// Validate that an uploaded file is exactly 512 kilobytes...

'image' => 'file|size:512';

starts_with:foo,bar,…

The field under validation must start with one of the given values.

string

The field under validation must be a string. If you would like to allow the field to also be null, you should assign the nullable rule to the field.

timezone

The field under validation must be a valid timezone identifier according to the timezone_identifiers_list PHP function.

unique:table,column

The field under validation must not exist within the given database table.

Specifying A Custom Table / Column Name:

Instead of specifying the table name directly, you may specify the Eloquent model which should be used to determine the table name:

'email' => 'unique:AppModelsUser,email_address'

The column option may be used to specify the field’s corresponding database column. If the column option is not specified, the name of the field under validation will be used.

'email' => 'unique:users,email_address'

Specifying A Custom Database Connection

Occasionally, you may need to set a custom connection for database queries made by the Validator. To accomplish this, you may prepend the connection name to the table name:

'email' => 'unique:connection.users,email_address'

Forcing A Unique Rule To Ignore A Given ID:

Sometimes, you may wish to ignore a given ID during unique validation. For example, consider an «update profile» screen that includes the user’s name, email address, and location. You will probably want to verify that the email address is unique. However, if the user only changes the name field and not the email field, you do not want a validation error to be thrown because the user is already the owner of the email address in question.

To instruct the validator to ignore the user’s ID, we’ll use the Rule class to fluently define the rule. In this example, we’ll also specify the validation rules as an array instead of using the | character to delimit the rules:

use IlluminateSupportFacadesValidator;

use IlluminateValidationRule;

Validator::make($data, [

'email' => [

'required',

Rule::unique('users')->ignore($user->id),

],

]);

Warning
You should never pass any user controlled request input into the ignore method. Instead, you should only pass a system generated unique ID such as an auto-incrementing ID or UUID from an Eloquent model instance. Otherwise, your application will be vulnerable to an SQL injection attack.

Instead of passing the model key’s value to the ignore method, you may also pass the entire model instance. Laravel will automatically extract the key from the model:

Rule::unique('users')->ignore($user)

If your table uses a primary key column name other than id, you may specify the name of the column when calling the ignore method:

Rule::unique('users')->ignore($user->id, 'user_id')

By default, the unique rule will check the uniqueness of the column matching the name of the attribute being validated. However, you may pass a different column name as the second argument to the unique method:

Rule::unique('users', 'email_address')->ignore($user->id),

Adding Additional Where Clauses:

You may specify additional query conditions by customizing the query using the where method. For example, let’s add a query condition that scopes the query to only search records that have an account_id column value of 1:

'email' => Rule::unique('users')->where(fn ($query) => $query->where('account_id', 1))

uppercase

The field under validation must be uppercase.

url

The field under validation must be a valid URL.

ulid

The field under validation must be a valid Universally Unique Lexicographically Sortable Identifier (ULID).

uuid

The field under validation must be a valid RFC 4122 (version 1, 3, 4, or 5) universally unique identifier (UUID).

Conditionally Adding Rules

Skipping Validation When Fields Have Certain Values

You may occasionally wish to not validate a given field if another field has a given value. You may accomplish this using the exclude_if validation rule. In this example, the appointment_date and doctor_name fields will not be validated if the has_appointment field has a value of false:

use IlluminateSupportFacadesValidator;

$validator = Validator::make($data, [

'has_appointment' => 'required|boolean',

'appointment_date' => 'exclude_if:has_appointment,false|required|date',

'doctor_name' => 'exclude_if:has_appointment,false|required|string',

]);

Alternatively, you may use the exclude_unless rule to not validate a given field unless another field has a given value:

$validator = Validator::make($data, [

'has_appointment' => 'required|boolean',

'appointment_date' => 'exclude_unless:has_appointment,true|required|date',

'doctor_name' => 'exclude_unless:has_appointment,true|required|string',

]);

Validating When Present

In some situations, you may wish to run validation checks against a field only if that field is present in the data being validated. To quickly accomplish this, add the sometimes rule to your rule list:

$v = Validator::make($data, [

'email' => 'sometimes|required|email',

]);

In the example above, the email field will only be validated if it is present in the $data array.

Note
If you are attempting to validate a field that should always be present but may be empty, check out this note on optional fields.

Complex Conditional Validation

Sometimes you may wish to add validation rules based on more complex conditional logic. For example, you may wish to require a given field only if another field has a greater value than 100. Or, you may need two fields to have a given value only when another field is present. Adding these validation rules doesn’t have to be a pain. First, create a Validator instance with your static rules that never change:

use IlluminateSupportFacadesValidator;

$validator = Validator::make($request->all(), [

'email' => 'required|email',

'games' => 'required|numeric',

]);

Let’s assume our web application is for game collectors. If a game collector registers with our application and they own more than 100 games, we want them to explain why they own so many games. For example, perhaps they run a game resale shop, or maybe they just enjoy collecting games. To conditionally add this requirement, we can use the sometimes method on the Validator instance.

$validator->sometimes('reason', 'required|max:500', function ($input) {

return $input->games >= 100;

});

The first argument passed to the sometimes method is the name of the field we are conditionally validating. The second argument is a list of the rules we want to add. If the closure passed as the third argument returns true, the rules will be added. This method makes it a breeze to build complex conditional validations. You may even add conditional validations for several fields at once:

$validator->sometimes(['reason', 'cost'], 'required', function ($input) {

return $input->games >= 100;

});

Note
The $input parameter passed to your closure will be an instance of IlluminateSupportFluent and may be used to access your input and files under validation.

Complex Conditional Array Validation

Sometimes you may want to validate a field based on another field in the same nested array whose index you do not know. In these situations, you may allow your closure to receive a second argument which will be the current individual item in the array being validated:

$input = [

'channels' => [

[

'type' => 'email',

'address' => '[email protected]',

],

[

'type' => 'url',

'address' => 'https://example.com',

],

],

];

$validator->sometimes('channels.*.address', 'email', function ($input, $item) {

return $item->type === 'email';

});

$validator->sometimes('channels.*.address', 'url', function ($input, $item) {

return $item->type !== 'email';

});

Like the $input parameter passed to the closure, the $item parameter is an instance of IlluminateSupportFluent when the attribute data is an array; otherwise, it is a string.

Validating Arrays

As discussed in the array validation rule documentation, the array rule accepts a list of allowed array keys. If any additional keys are present within the array, validation will fail:

use IlluminateSupportFacadesValidator;

$input = [

'user' => [

'name' => 'Taylor Otwell',

'username' => 'taylorotwell',

'admin' => true,

],

];

Validator::make($input, [

'user' => 'array:username,locale',

]);

In general, you should always specify the array keys that are allowed to be present within your array. Otherwise, the validator’s validate and validated methods will return all of the validated data, including the array and all of its keys, even if those keys were not validated by other nested array validation rules.

Validating Nested Array Input

Validating nested array based form input fields doesn’t have to be a pain. You may use «dot notation» to validate attributes within an array. For example, if the incoming HTTP request contains a photos[profile] field, you may validate it like so:

use IlluminateSupportFacadesValidator;

$validator = Validator::make($request->all(), [

'photos.profile' => 'required|image',

]);

You may also validate each element of an array. For example, to validate that each email in a given array input field is unique, you may do the following:

$validator = Validator::make($request->all(), [

'person.*.email' => 'email|unique:users',

'person.*.first_name' => 'required_with:person.*.last_name',

]);

Likewise, you may use the * character when specifying custom validation messages in your language files, making it a breeze to use a single validation message for array based fields:

'custom' => [

'person.*.email' => [

'unique' => 'Each person must have a unique email address',

]

],

Accessing Nested Array Data

Sometimes you may need to access the value for a given nested array element when assigning validation rules to the attribute. You may accomplish this using the Rule::forEach method. The forEach method accepts a closure that will be invoked for each iteration of the array attribute under validation and will receive the attribute’s value and explicit, fully-expanded attribute name. The closure should return an array of rules to assign to the array element:

use AppRulesHasPermission;

use IlluminateSupportFacadesValidator;

use IlluminateValidationRule;

$validator = Validator::make($request->all(), [

'companies.*.id' => Rule::forEach(function ($value, $attribute) {

return [

Rule::exists(Company::class, 'id'),

new HasPermission('manage-company', $value),

];

}),

]);

Error Message Indexes & Positions

When validating arrays, you may want to reference the index or position of a particular item that failed validation within the error message displayed by your application. To accomplish this, you may include the :index (starts from 0) and :position (starts from 1) placeholders within your custom validation message:

use IlluminateSupportFacadesValidator;

$input = [

'photos' => [

[

'name' => 'BeachVacation.jpg',

'description' => 'A photo of my beach vacation!',

],

[

'name' => 'GrandCanyon.jpg',

'description' => '',

],

],

];

Validator::validate($input, [

'photos.*.description' => 'required',

], [

'photos.*.description.required' => 'Please describe photo #:position.',

]);

Given the example above, validation will fail and the user will be presented with the following error of «Please describe photo #2.»

Validating Files

Laravel provides a variety of validation rules that may be used to validate uploaded files, such as mimes, image, min, and max. While you are free to specify these rules individually when validating files, Laravel also offers a fluent file validation rule builder that you may find convenient:

use IlluminateSupportFacadesValidator;

use IlluminateValidationRulesFile;

Validator::validate($input, [

'attachment' => [

'required',

File::types(['mp3', 'wav'])

->min(1024)

->max(12 * 1024),

],

]);

If your application accepts images uploaded by your users, you may use the File rule’s image constructor method to indicate that the uploaded file should be an image. In addition, the dimensions rule may be used to limit the dimensions of the image:

use IlluminateSupportFacadesValidator;

use IlluminateValidationRulesFile;

Validator::validate($input, [

'photo' => [

'required',

File::image()

->min(1024)

->max(12 * 1024)

->dimensions(Rule::dimensions()->maxWidth(1000)->maxHeight(500)),

],

]);

Note
More information regarding validating image dimensions may be found in the dimension rule documentation.

File Types

Even though you only need to specify the extensions when invoking the types method, this method actually validates the MIME type of the file by reading the file’s contents and guessing its MIME type. A full listing of MIME types and their corresponding extensions may be found at the following location:

https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types

Validating Passwords

To ensure that passwords have an adequate level of complexity, you may use Laravel’s Password rule object:

use IlluminateSupportFacadesValidator;

use IlluminateValidationRulesPassword;

$validator = Validator::make($request->all(), [

'password' => ['required', 'confirmed', Password::min(8)],

]);

The Password rule object allows you to easily customize the password complexity requirements for your application, such as specifying that passwords require at least one letter, number, symbol, or characters with mixed casing:

// Require at least 8 characters...

Password::min(8)

// Require at least one letter...

Password::min(8)->letters()

// Require at least one uppercase and one lowercase letter...

Password::min(8)->mixedCase()

// Require at least one number...

Password::min(8)->numbers()

// Require at least one symbol...

Password::min(8)->symbols()

In addition, you may ensure that a password has not been compromised in a public password data breach leak using the uncompromised method:

Password::min(8)->uncompromised()

Internally, the Password rule object uses the k-Anonymity model to determine if a password has been leaked via the haveibeenpwned.com service without sacrificing the user’s privacy or security.

By default, if a password appears at least once in a data leak, it will be considered compromised. You can customize this threshold using the first argument of the uncompromised method:

// Ensure the password appears less than 3 times in the same data leak...

Password::min(8)->uncompromised(3);

Of course, you may chain all the methods in the examples above:

Password::min(8)

->letters()

->mixedCase()

->numbers()

->symbols()

->uncompromised()

Defining Default Password Rules

You may find it convenient to specify the default validation rules for passwords in a single location of your application. You can easily accomplish this using the Password::defaults method, which accepts a closure. The closure given to the defaults method should return the default configuration of the Password rule. Typically, the defaults rule should be called within the boot method of one of your application’s service providers:

use IlluminateValidationRulesPassword;

/**

* Bootstrap any application services.

*

* @return void

*/

public function boot()

{

Password::defaults(function () {

$rule = Password::min(8);

return $this->app->isProduction()

? $rule->mixedCase()->uncompromised()

: $rule;

});

}

Then, when you would like to apply the default rules to a particular password undergoing validation, you may invoke the defaults method with no arguments:

'password' => ['required', Password::defaults()],

Occasionally, you may want to attach additional validation rules to your default password validation rules. You may use the rules method to accomplish this:

use AppRulesZxcvbnRule;

Password::defaults(function () {

$rule = Password::min(8)->rules([new ZxcvbnRule]);

// ...

});

Custom Validation Rules

Using Rule Objects

Laravel provides a variety of helpful validation rules; however, you may wish to specify some of your own. One method of registering custom validation rules is using rule objects. To generate a new rule object, you may use the make:rule Artisan command. Let’s use this command to generate a rule that verifies a string is uppercase. Laravel will place the new rule in the app/Rules directory. If this directory does not exist, Laravel will create it when you execute the Artisan command to create your rule:

php artisan make:rule Uppercase --invokable

Once the rule has been created, we are ready to define its behavior. A rule object contains a single method: __invoke. This method receives the attribute name, its value, and a callback that should be invoked on failure with the validation error message:

<?php

namespace AppRules;

use IlluminateContractsValidationInvokableRule;

class Uppercase implements InvokableRule

{

/**

* Run the validation rule.

*

* @param string $attribute

* @param mixed $value

* @param Closure $fail

* @return void

*/

public function __invoke($attribute, $value, $fail)

{

if (strtoupper($value) !== $value) {

$fail('The :attribute must be uppercase.');

}

}

}

Once the rule has been defined, you may attach it to a validator by passing an instance of the rule object with your other validation rules:

use AppRulesUppercase;

$request->validate([

'name' => ['required', 'string', new Uppercase],

]);

Translating Validation Messages

Instead of providing a literal error message to the $fail closure, you may also provide a translation string key and instruct Laravel to translate the error message:

if (strtoupper($value) !== $value) {

$fail('validation.uppercase')->translate();

}

If necessary, you may provide placeholder replacements and the preferred language as the first and second arguments to the translate method:

$fail('validation.location')->translate([

'value' => $this->value,

], 'fr')

Accessing Additional Data

If your custom validation rule class needs to access all of the other data undergoing validation, your rule class may implement the IlluminateContractsValidationDataAwareRule interface. This interface requires your class to define a setData method. This method will automatically be invoked by Laravel (before validation proceeds) with all of the data under validation:

<?php

namespace AppRules;

use IlluminateContractsValidationDataAwareRule;

use IlluminateContractsValidationInvokableRule;

class Uppercase implements DataAwareRule, InvokableRule

{

/**

* All of the data under validation.

*

* @var array

*/

protected $data = [];

// ...

/**

* Set the data under validation.

*

* @param array $data

* @return $this

*/

public function setData($data)

{

$this->data = $data;

return $this;

}

}

Or, if your validation rule requires access to the validator instance performing the validation, you may implement the ValidatorAwareRule interface:

<?php

namespace AppRules;

use IlluminateContractsValidationInvokableRule;

use IlluminateContractsValidationValidatorAwareRule;

class Uppercase implements InvokableRule, ValidatorAwareRule

{

/**

* The validator instance.

*

* @var IlluminateValidationValidator

*/

protected $validator;

// ...

/**

* Set the current validator.

*

* @param IlluminateValidationValidator $validator

* @return $this

*/

public function setValidator($validator)

{

$this->validator = $validator;

return $this;

}

}

Using Closures

If you only need the functionality of a custom rule once throughout your application, you may use a closure instead of a rule object. The closure receives the attribute’s name, the attribute’s value, and a $fail callback that should be called if validation fails:

use IlluminateSupportFacadesValidator;

$validator = Validator::make($request->all(), [

'title' => [

'required',

'max:255',

function ($attribute, $value, $fail) {

if ($value === 'foo') {

$fail('The '.$attribute.' is invalid.');

}

},

],

]);

Implicit Rules

By default, when an attribute being validated is not present or contains an empty string, normal validation rules, including custom rules, are not run. For example, the unique rule will not be run against an empty string:

use IlluminateSupportFacadesValidator;

$rules = ['name' => 'unique:users,name'];

$input = ['name' => ''];

Validator::make($input, $rules)->passes(); // true

For a custom rule to run even when an attribute is empty, the rule must imply that the attribute is required. To quickly generate a new implicit rule object, you may use the make:rule Artisan command with the --implicit option:

php artisan make:rule Uppercase --invokable --implicit

Warning
An «implicit» rule only implies that the attribute is required. Whether it actually invalidates a missing or empty attribute is up to you.

  • Introduction
  • Validation Quickstart
    • Defining The Routes
    • Creating The Controller
    • Writing The Validation Logic
    • Displaying The Validation Errors
    • A Note On Optional Fields
  • Form Request Validation
    • Creating Form Requests
    • Authorizing Form Requests
    • Customizing The Error Format
    • Customizing The Error Messages
  • Manually Creating Validators
    • Automatic Redirection
    • Named Error Bags
    • After Validation Hook
  • Working With Error Messages
    • Custom Error Messages
  • Available Validation Rules
  • Conditionally Adding Rules
  • Validating Arrays
  • Custom Validation Rules

Introduction

Laravel provides several different approaches to validate your application’s incoming data. By default, Laravel’s base controller class uses a ValidatesRequests trait which provides a convenient method to validate incoming HTTP request with a variety of powerful validation rules.

Validation Quickstart

To learn about Laravel’s powerful validation features, let’s look at a complete example of validating a form and displaying the error messages back to the user.

Defining The Routes

First, let’s assume we have the following routes defined in our routes/web.php file:

Route::get('post/create', 'PostController@create');

Route::post('post', 'PostController@store');

Of course, the GET route will display a form for the user to create a new blog post, while the POST route will store the new blog post in the database.

Creating The Controller

Next, let’s take a look at a simple controller that handles these routes. We’ll leave the store method empty for now:

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppHttpControllersController;

class PostController extends Controller
{
    /**
     * Show the form to create a new blog post.
     *
     * @return Response
     */
    public function create()
    {
        return view('post.create');
    }

    /**
     * Store a new blog post.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        // Validate and store the blog post...
    }
}

Writing The Validation Logic

Now we are ready to fill in our store method with the logic to validate the new blog post. If you examine your application’s base controller (AppHttpControllersController) class, you will see that the class uses a ValidatesRequests trait. This trait provides a convenient validate method to all of your controllers.

The validate method accepts an incoming HTTP request and a set of validation rules. If the validation rules pass, your code will keep executing normally; however, if validation fails, an exception will be thrown and the proper error response will automatically be sent back to the user. In the case of a traditional HTTP request, a redirect response will be generated, while a JSON response will be sent for AJAX requests.

To get a better understanding of the validate method, let’s jump back into the store method:

/**
 * Store a new blog post.
 *
 * @param  Request  $request
 * @return Response
 */
public function store(Request $request)
{
    $this->validate($request, [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);

    // The blog post is valid, store in database...
}

As you can see, we simply pass the incoming HTTP request and desired validation rules into the validate method. Again, if the validation fails, the proper response will automatically be generated. If the validation passes, our controller will continue executing normally.

Stopping On First Validation Failure

Sometimes you may wish to stop running validation rules on an attribute after the first validation failure. To do so, assign the bail rule to the attribute:

$this->validate($request, [
    'title' => 'bail|required|unique:posts|max:255',
    'body' => 'required',
]);

In this example, if the required rule on the title attribute fails, the unique rule will not be checked. Rules will be validated in the order they are assigned.

A Note On Nested Attributes

If your HTTP request contains «nested» parameters, you may specify them in your validation rules using «dot» syntax:

$this->validate($request, [
    'title' => 'required|unique:posts|max:255',
    'author.name' => 'required',
    'author.description' => 'required',
]);

Displaying The Validation Errors

So, what if the incoming request parameters do not pass the given validation rules? As mentioned previously, Laravel will automatically redirect the user back to their previous location. In addition, all of the validation errors will automatically be flashed to the session.

Again, notice that we did not have to explicitly bind the error messages to the view in our GET route. This is because Laravel will check for errors in the session data, and automatically bind them to the view if they are available. The $errors variable will be an instance of IlluminateSupportMessageBag. For more information on working with this object, check out its documentation.

{tip} The $errors variable is bound to the view by the IlluminateViewMiddlewareShareErrorsFromSession middleware, which is provided by the web middleware group. When this middleware is applied an $errors variable will always be available in your views, allowing you to conveniently assume the $errors variable is always defined and can be safely used.

So, in our example, the user will be redirected to our controller’s create method when validation fails, allowing us to display the error messages in the view:

<!-- /resources/views/post/create.blade.php -->

<h1>Create Post</h1>

@if (count($errors) > 0)
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

<!-- Create Post Form -->

A Note On Optional Fields

By default, Laravel includes the TrimStrings and ConvertEmptyStringsToNull middleware in your application’s global middleware stack. These middleware are listed in the stack by the AppHttpKernel class. Because of this, you will often need to mark your «optional» request fields as nullable if you do not want the validator to consider null values as invalid. For example:

$this->validate($request, [
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
    'publish_at' => 'nullable|date',
]);

In this example, we are specifying that the publish_at field may be either null or a valid date representation. If the nullable modifier is not added to the rule definition, the validator would consider null an invalid date.

Customizing The Flashed Error Format

If you wish to customize the format of the validation errors that are flashed to the session when validation fails, override the formatValidationErrors on your base controller. Don’t forget to import the IlluminateContractsValidationValidator class at the top of the file:

<?php

namespace AppHttpControllers;

use IlluminateFoundationBusDispatchesJobs;
use IlluminateContractsValidationValidator;
use IlluminateRoutingController as BaseController;
use IlluminateFoundationValidationValidatesRequests;

abstract class Controller extends BaseController
{
    use DispatchesJobs, ValidatesRequests;

    /**
     * {@inheritdoc}
     */
    protected function formatValidationErrors(Validator $validator)
    {
        return $validator->errors()->all();
    }
}

AJAX Requests & Validation

In this example, we used a traditional form to send data to the application. However, many applications use AJAX requests. When using the validate method during an AJAX request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.

Form Request Validation

Creating Form Requests

For more complex validation scenarios, you may wish to create a «form request». Form requests are custom request classes that contain validation logic. To create a form request class, use the make:request Artisan CLI command:

php artisan make:request StoreBlogPost

The generated class will be placed in the app/Http/Requests directory. If this directory does not exist, it will be created when you run the make:request command. Let’s add a few validation rules to the rules method:

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    return [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ];
}

So, how are the validation rules evaluated? All you need to do is type-hint the request on your controller method. The incoming form request is validated before the controller method is called, meaning you do not need to clutter your controller with any validation logic:

/**
 * Store the incoming blog post.
 *
 * @param  StoreBlogPost  $request
 * @return Response
 */
public function store(StoreBlogPost $request)
{
    // The incoming request is valid...
}

If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an AJAX request, a HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.

Adding After Hooks To Form Requests

If you would like to add an «after» hook to a form request, you may use the withValidator method. This method receives the fully constructed validator, allowing you to call any of its methods before the validation rules are actually evaluated:

/**
 * Configure the validator instance.
 *
 * @param  IlluminateValidationValidator  $validator
 * @return void
 */
public function withValidator($validator)
{
    $validator->after(function ($validator) {
        if ($this->somethingElseIsInvalid()) {
            $validator->errors()->add('field', 'Something is wrong with this field!');
        }
    });
}

The form request class also contains an authorize method. Within this method, you may check if the authenticated user actually has the authority to update a given resource. For example, you may determine if a user actually owns a blog comment they are attempting to update:

/**
 * Determine if the user is authorized to make this request.
 *
 * @return bool
 */
public function authorize()
{
    $comment = Comment::find($this->route('comment'));

    return $comment && $this->user()->can('update', $comment);
}

Since all form requests extend the base Laravel request class, we may use the user method to access the currently authenticated user. Also note the call to the route method in the example above. This method grants you access to the URI parameters defined on the route being called, such as the {comment} parameter in the example below:

Route::post('comment/{comment}');

If the authorize method returns false, a HTTP response with a 403 status code will automatically be returned and your controller method will not execute.

If you plan to have authorization logic in another part of your application, simply return true from the authorize method:

/**
 * Determine if the user is authorized to make this request.
 *
 * @return bool
 */
public function authorize()
{
    return true;
}

Customizing The Error Format

If you wish to customize the format of the validation errors that are flashed to the session when validation fails, override the formatErrors on your base request (AppHttpRequestsRequest). Don’t forget to import the IlluminateContractsValidationValidator class at the top of the file:

/**
 * {@inheritdoc}
 */
protected function formatErrors(Validator $validator)
{
    return $validator->errors()->all();
}

Customizing The Error Messages

You may customize the error messages used by the form request by overriding the messages method. This method should return an array of attribute / rule pairs and their corresponding error messages:

/**
 * Get the error messages for the defined validation rules.
 *
 * @return array
 */
public function messages()
{
    return [
        'title.required' => 'A title is required',
        'body.required'  => 'A message is required',
    ];
}

Manually Creating Validators

If you do not want to use the ValidatesRequests trait’s validate method, you may create a validator instance manually using the Validator facade. The make method on the facade generates a new validator instance:

<?php

namespace AppHttpControllers;

use Validator;
use IlluminateHttpRequest;
use AppHttpControllersController;

class PostController extends Controller
{
    /**
     * Store a new blog post.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
        ]);

        if ($validator->fails()) {
            return redirect('post/create')
                        ->withErrors($validator)
                        ->withInput();
        }

        // Store the blog post...
    }
}

The first argument passed to the make method is the data under validation. The second argument is the validation rules that should be applied to the data.

After checking if the request validation failed, you may use the withErrors method to flash the error messages to the session. When using this method, the $errors variable will automatically be shared with your views after redirection, allowing you to easily display them back to the user. The withErrors method accepts a validator, a MessageBag, or a PHP array.

Automatic Redirection

If you would like to create a validator instance manually but still take advantage of the automatic redirection offered by the ValidatesRequest trait, you may call the validate method on an existing validator instance. If validation fails, the user will automatically be redirected or, in the case of an AJAX request, a JSON response will be returned:

Validator::make($request->all(), [
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
])->validate();

Named Error Bags

If you have multiple forms on a single page, you may wish to name the MessageBag of errors, allowing you to retrieve the error messages for a specific form. Simply pass a name as the second argument to withErrors:

return redirect('register')
            ->withErrors($validator, 'login');

You may then access the named MessageBag instance from the $errors variable:

{{ $errors->login->first('email') }}

After Validation Hook

The validator also allows you to attach callbacks to be run after validation is completed. This allows you to easily perform further validation and even add more error messages to the message collection. To get started, use the after method on a validator instance:

$validator = Validator::make(...);

$validator->after(function ($validator) {
    if ($this->somethingElseIsInvalid()) {
        $validator->errors()->add('field', 'Something is wrong with this field!');
    }
});

if ($validator->fails()) {
    //
}

Working With Error Messages

After calling the errors method on a Validator instance, you will receive an IlluminateSupportMessageBag instance, which has a variety of convenient methods for working with error messages. The $errors variable that is automatically made available to all views is also an instance of the MessageBag class.

Retrieving The First Error Message For A Field

To retrieve the first error message for a given field, use the first method:

$errors = $validator->errors();

echo $errors->first('email');

Retrieving All Error Messages For A Field

If you need to retrieve an array of all the messages for a given field, use the get method:

foreach ($errors->get('email') as $message) {
    //
}

If you are validating an array form field, you may retrieve all of the messages for each of the array elements using the * character:

foreach ($errors->get('attachments.*') as $message) {
    //
}

Retrieving All Error Messages For All Fields

To retrieve an array of all messages for all fields, use the all method:

foreach ($errors->all() as $message) {
    //
}

Determining If Messages Exist For A Field

The has method may be used to determine if any error messages exist for a given field:

if ($errors->has('email')) {
    //
}

Custom Error Messages

If needed, you may use custom error messages for validation instead of the defaults. There are several ways to specify custom messages. First, you may pass the custom messages as the third argument to the Validator::make method:

$messages = [
    'required' => 'The :attribute field is required.',
];

$validator = Validator::make($input, $rules, $messages);

In this example, the :attribute place-holder will be replaced by the actual name of the field under validation. You may also utilize other place-holders in validation messages. For example:

$messages = [
    'same'    => 'The :attribute and :other must match.',
    'size'    => 'The :attribute must be exactly :size.',
    'between' => 'The :attribute must be between :min - :max.',
    'in'      => 'The :attribute must be one of the following types: :values',
];

Specifying A Custom Message For A Given Attribute

Sometimes you may wish to specify a custom error messages only for a specific field. You may do so using «dot» notation. Specify the attribute’s name first, followed by the rule:

$messages = [
    'email.required' => 'We need to know your e-mail address!',
];

Specifying Custom Messages In Language Files

In most cases, you will probably specify your custom messages in a language file instead of passing them directly to the Validator. To do so, add your messages to custom array in the resources/lang/xx/validation.php language file.

'custom' => [
    'email' => [
        'required' => 'We need to know your e-mail address!',
    ],
],

Specifying Custom Attributes In Language Files

If you would like the :attribute portion of your validation message to be replaced with a custom attribute name, you may specify the custom name in the attributes array of your resources/lang/xx/validation.php language file:

'attributes' => [
    'email' => 'email address',
],

Available Validation Rules

Below is a list of all available validation rules and their function:

[Accepted](#rule-accepted)
[Active URL](#rule-active-url)
[After (Date)](#rule-after)
[After Or Equal (Date)](#rule-after-or-equal)
[Alpha](#rule-alpha)
[Alpha Dash](#rule-alpha-dash)
[Alpha Numeric](#rule-alpha-num)
[Array](#rule-array)
[Before (Date)](#rule-before)
[Before Or Equal (Date)](#rule-before-or-equal)
[Between](#rule-between)
[Boolean](#rule-boolean)
[Confirmed](#rule-confirmed)
[Date](#rule-date)
[Date Format](#rule-date-format)
[Different](#rule-different)
[Digits](#rule-digits)
[Digits Between](#rule-digits-between)
[Dimensions (Image Files)](#rule-dimensions)
[Distinct](#rule-distinct)
[E-Mail](#rule-email)
[Exists (Database)](#rule-exists)
[File](#rule-file)
[Filled](#rule-filled)
[Image (File)](#rule-image)
[In](#rule-in)
[In Array](#rule-in-array)
[Integer](#rule-integer)
[IP Address](#rule-ip)
[JSON](#rule-json)
[Max](#rule-max)
[MIME Types](#rule-mimetypes)
[MIME Type By File Extension](#rule-mimes)
[Min](#rule-min)
[Nullable](#rule-nullable)
[Not In](#rule-not-in)
[Numeric](#rule-numeric)
[Present](#rule-present)
[Regular Expression](#rule-regex)
[Required](#rule-required)
[Required If](#rule-required-if)
[Required Unless](#rule-required-unless)
[Required With](#rule-required-with)
[Required With All](#rule-required-with-all)
[Required Without](#rule-required-without)
[Required Without All](#rule-required-without-all)
[Same](#rule-same)
[Size](#rule-size)
[String](#rule-string)
[Timezone](#rule-timezone)
[Unique (Database)](#rule-unique)
[URL](#rule-url)

accepted

The field under validation must be yes, on, 1, or true. This is useful for validating «Terms of Service» acceptance.

active_url

The field under validation must have a valid A or AAAA record according to the dns_get_record PHP function.

after:date

The field under validation must be a value after a given date. The dates will be passed into the strtotime PHP function:

'start_date' => 'required|date|after:tomorrow'

Instead of passing a date string to be evaluated by strtotime, you may specify another field to compare against the date:

'finish_date' => 'required|date|after:start_date'

after_or_equal:date

The field under validation must be a value after or equal to the given date. For more information, see the after rule.

alpha

The field under validation must be entirely alphabetic characters.

alpha_dash

The field under validation may have alpha-numeric characters, as well as dashes and underscores.

alpha_num

The field under validation must be entirely alpha-numeric characters.

array

The field under validation must be a PHP array.

before:date

The field under validation must be a value preceding the given date. The dates will be passed into the PHP strtotime function.

before_or_equal:date

The field under validation must be a value preceding or equal to the given date. The dates will be passed into the PHP strtotime function.

between:min,max

The field under validation must have a size between the given min and max. Strings, numerics, and files are evaluated in the same fashion as the size rule.

boolean

The field under validation must be able to be cast as a boolean. Accepted input are true, false, 1, 0, "1", and "0".

confirmed

The field under validation must have a matching field of foo_confirmation. For example, if the field under validation is password, a matching password_confirmation field must be present in the input.

date

The field under validation must be a valid date according to the strtotime PHP function.

date_format:format

The field under validation must match the given format. You should use either date or date_format when validating a field, not both.

different:field

The field under validation must have a different value than field.

digits:value

The field under validation must be numeric and must have an exact length of value.

digits_between:min,max

The field under validation must have a length between the given min and max.

dimensions

The file under validation must be an image meeting the dimension constraints as specified by the rule’s parameters:

'avatar' => 'dimensions:min_width=100,min_height=200'

Available constraints are: min_width, max_width, min_height, max_height, width, height, ratio.

A ratio constraint should be represented as width divided by height. This can be specified either by a statement like 3/2 or a float like 1.5:

'avatar' => 'dimensions:ratio=3/2'

Since this rule requires several arguments, you may use the Rule::dimensions method to fluently construct the rule:

use IlluminateValidationRule;

Validator::make($data, [
    'avatar' => [
        'required',
        Rule::dimensions()->maxWidth(1000)->maxHeight(500)->ratio(3 / 2),
    ],
]);

distinct

When working with arrays, the field under validation must not have any duplicate values.

'foo.*.id' => 'distinct'

email

The field under validation must be formatted as an e-mail address.

exists:table,column

The field under validation must exist on a given database table.

Basic Usage Of Exists Rule

'state' => 'exists:states'

Specifying A Custom Column Name

'state' => 'exists:states,abbreviation'

Occasionally, you may need to specify a specific database connection to be used for the exists query. You can accomplish this by prepending the connection name to the table name using «dot» syntax:

'email' => 'exists:connection.staff,email'

If you would like to customize the query executed by the validation rule, you may use the Rule class to fluently define the rule. In this example, we’ll also specify the validation rules as an array instead of using the | character to delimit them:

use IlluminateValidationRule;

Validator::make($data, [
    'email' => [
        'required',
        Rule::exists('staff')->where(function ($query) {
            $query->where('account_id', 1);
        }),
    ],
]);

file

The field under validation must be a successfully uploaded file.

filled

The field under validation must not be empty when it is present.

image

The file under validation must be an image (jpeg, png, bmp, gif, or svg)

in:foo,bar,…

The field under validation must be included in the given list of values. Since this rule often requires you to implode an array, the Rule::in method may be used to fluently construct the rule:

use IlluminateValidationRule;

Validator::make($data, [
    'zones' => [
        'required',
        Rule::in(['first-zone', 'second-zone']),
    ],
]);

in_array:anotherfield

The field under validation must exist in anotherfield‘s values.

integer

The field under validation must be an integer.

ip

The field under validation must be an IP address.

ipv4

The field under validation must be an IPv4 address.

ipv6

The field under validation must be an IPv6 address.

json

The field under validation must be a valid JSON string.

max:value

The field under validation must be less than or equal to a maximum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.

mimetypes:text/plain,…

The file under validation must match one of the given MIME types:

'video' => 'mimetypes:video/avi,video/mpeg,video/quicktime'

To determine the MIME type of the uploaded file, the file’s contents will be read and the framework will attempt to guess the MIME type, which may be different from the client provided MIME type.

mimes:foo,bar,…

The file under validation must have a MIME type corresponding to one of the listed extensions.

Basic Usage Of MIME Rule

'photo' => 'mimes:jpeg,bmp,png'

Even though you only need to specify the extensions, this rule actually validates against the MIME type of the file by reading the file’s contents and guessing its MIME type.

A full listing of MIME types and their corresponding extensions may be found at the following location: https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types

min:value

The field under validation must have a minimum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.

nullable

The field under validation may be null. This is particularly useful when validating primitive such as strings and integers that can contain null values.

not_in:foo,bar,…

The field under validation must not be included in the given list of values.

numeric

The field under validation must be numeric.

present

The field under validation must be present in the input data but can be empty.

regex:pattern

The field under validation must match the given regular expression.

Note: When using the regex pattern, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character.

required

The field under validation must be present in the input data and not empty. A field is considered «empty» if one of the following conditions are true:

— The value is `null`.
— The value is an empty string.
— The value is an empty array or empty `Countable` object.
— The value is an uploaded file with no path.

required_if:anotherfield,value,…

The field under validation must be present and not empty if the anotherfield field is equal to any value.

required_unless:anotherfield,value,…

The field under validation must be present and not empty unless the anotherfield field is equal to any value.

required_with:foo,bar,…

The field under validation must be present and not empty only if any of the other specified fields are present.

required_with_all:foo,bar,…

The field under validation must be present and not empty only if all of the other specified fields are present.

required_without:foo,bar,…

The field under validation must be present and not empty only when any of the other specified fields are not present.

required_without_all:foo,bar,…

The field under validation must be present and not empty only when all of the other specified fields are not present.

same:field

The given field must match the field under validation.

size:value

The field under validation must have a size matching the given value. For string data, value corresponds to the number of characters. For numeric data, value corresponds to a given integer value. For an array, size corresponds to the count of the array. For files, size corresponds to the file size in kilobytes.

string

The field under validation must be a string. If you would like to allow the field to also be null, you should assign the nullable rule to the field.

timezone

The field under validation must be a valid timezone identifier according to the timezone_identifiers_list PHP function.

unique:table,column,except,idColumn

The field under validation must be unique in a given database table. If the column option is not specified, the field name will be used.

Specifying A Custom Column Name:

'email' => 'unique:users,email_address'

Custom Database Connection

Occasionally, you may need to set a custom connection for database queries made by the Validator. As seen above, setting unique:users as a validation rule will use the default database connection to query the database. To override this, specify the connection and the table name using «dot» syntax:

'email' => 'unique:connection.users,email_address'

Forcing A Unique Rule To Ignore A Given ID:

Sometimes, you may wish to ignore a given ID during the unique check. For example, consider an «update profile» screen that includes the user’s name, e-mail address, and location. Of course, you will want to verify that the e-mail address is unique. However, if the user only changes the name field and not the e-mail field, you do not want a validation error to be thrown because the user is already the owner of the e-mail address.

To instruct the validator to ignore the user’s ID, we’ll use the Rule class to fluently define the rule. In this example, we’ll also specify the validation rules as an array instead of using the | character to delimit the rules:

use IlluminateValidationRule;

Validator::make($data, [
    'email' => [
        'required',
        Rule::unique('users')->ignore($user->id),
    ],
]);

If your table uses a primary key column name other than id, you may specify the name of the column when calling the ignore method:

'email' => Rule::unique('users')->ignore($user->id, 'user_id')

Adding Additional Where Clauses:

You may also specify additional query constraints by customizing the query using the where method. For example, let’s add a constraint that verifies the account_id is 1:

'email' => Rule::unique('users')->where(function ($query) {
    $query->where('account_id', 1);
})

url

The field under validation must be a valid URL.

Conditionally Adding Rules

Validating When Present

In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule to your rule list:

$v = Validator::make($data, [
    'email' => 'sometimes|required|email',
]);

In the example above, the email field will only be validated if it is present in the $data array.

Complex Conditional Validation

Sometimes you may wish to add validation rules based on more complex conditional logic. For example, you may wish to require a given field only if another field has a greater value than 100. Or, you may need two fields to have a given value only when another field is present. Adding these validation rules doesn’t have to be a pain. First, create a Validator instance with your static rules that never change:

$v = Validator::make($data, [
    'email' => 'required|email',
    'games' => 'required|numeric',
]);

Let’s assume our web application is for game collectors. If a game collector registers with our application and they own more than 100 games, we want them to explain why they own so many games. For example, perhaps they run a game resale shop, or maybe they just enjoy collecting. To conditionally add this requirement, we can use the sometimes method on the Validator instance.

$v->sometimes('reason', 'required|max:500', function ($input) {
    return $input->games >= 100;
});

The first argument passed to the sometimes method is the name of the field we are conditionally validating. The second argument is the rules we want to add. If the Closure passed as the third argument returns true, the rules will be added. This method makes it a breeze to build complex conditional validations. You may even add conditional validations for several fields at once:

$v->sometimes(['reason', 'cost'], 'required', function ($input) {
    return $input->games >= 100;
});

{tip} The $input parameter passed to your Closure will be an instance of IlluminateSupportFluent and may be used to access your input and files.

Validating Arrays

Validating array based form input fields doesn’t have to be a pain. For example, to validate that each e-mail in a given array input field is unique, you may do the following:

$validator = Validator::make($request->all(), [
    'person.*.email' => 'email|unique:users',
    'person.*.first_name' => 'required_with:person.*.last_name',
]);

Likewise, you may use the * character when specifying your validation messages in your language files, making it a breeze to use a single validation message for array based fields:

'custom' => [
    'person.*.email' => [
        'unique' => 'Each person must have a unique e-mail address',
    ]
],

Custom Validation Rules

Laravel provides a variety of helpful validation rules; however, you may wish to specify some of your own. One method of registering custom validation rules is using the extend method on the Validator facade. Let’s use this method within a service provider to register a custom validation rule:

<?php

namespace AppProviders;

use IlluminateSupportServiceProvider;
use IlluminateSupportFacadesValidator;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Validator::extend('foo', function ($attribute, $value, $parameters, $validator) {
            return $value == 'foo';
        });
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

The custom validator Closure receives four arguments: the name of the $attribute being validated, the $value of the attribute, an array of $parameters passed to the rule, and the Validator instance.

You may also pass a class and method to the extend method instead of a Closure:

Validator::extend('foo', 'FooValidator@validate');

Defining The Error Message

You will also need to define an error message for your custom rule. You can do so either using an inline custom message array or by adding an entry in the validation language file. This message should be placed in the first level of the array, not within the custom array, which is only for attribute-specific error messages:

"foo" => "Your input was invalid!",

"accepted" => "The :attribute must be accepted.",

// The rest of the validation error messages...

When creating a custom validation rule, you may sometimes need to define custom place-holder replacements for error messages. You may do so by creating a custom Validator as described above then making a call to the replacer method on the Validator facade. You may do this within the boot method of a service provider:

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    Validator::extend(...);

    Validator::replacer('foo', function ($message, $attribute, $rule, $parameters) {
        return str_replace(...);
    });
}

Implicit Extensions

By default, when an attribute being validated is not present or contains an empty value as defined by the required rule, normal validation rules, including custom extensions, are not run. For example, the unique rule will not be run against a null value:

$rules = ['name' => 'unique'];

$input = ['name' => null];

Validator::make($input, $rules)->passes(); // true

For a rule to run even when an attribute is empty, the rule must imply that the attribute is required. To create such an «implicit» extension, use the Validator::extendImplicit() method:

Validator::extendImplicit('foo', function ($attribute, $value, $parameters, $validator) {
    return $value == 'foo';
});

{note} An «implicit» extension only implies that the attribute is required. Whether it actually invalidates a missing or empty attribute is up to you.

  1. 1. Основы использования
  2. 2. Работа с сообщениями об ошибках
  3. 3. Ошибки и шаблоны

    1. 3.1. Именованные наборы ошибок
  4. 4. Доступные правила проверки

    1. 4.1. accepted
    2. 4.2. active_url
    3. 4.3. after:date
    4. 4.4. alpha
    5. 4.5. alpha_dash
    6. 4.6. alpha_num
    7. 4.7. array
    8. 4.8. before:date
    9. 4.9. between:min,max
    10. 4.10. boolean
    11. 4.11. confirmed
    12. 4.12. date
    13. 4.13. date_format:format
    14. 4.14. different:field
    15. 4.15. digits:value
    16. 4.16. digits_between:min,max
    17. 4.17. email
    18. 4.18. exists:table,column
    19. 4.19. image
    20. 4.20. in:foo,bar,…
    21. 4.21. integer
    22. 4.22. ip
    23. 4.23. max:value
    24. 4.24. mimes:foo,bar,…
    25. 4.25. min:value
    26. 4.26. not_in:foo,bar,…
    27. 4.27. numeric
    28. 4.28. regex:pattern
    29. 4.29. required
    30. 4.30. required_if:field,value,…
    31. 4.31. required_with:foo,bar,…
    32. 4.32. required_with_all:foo,bar,…
    33. 4.33. required_without:foo,bar,…
    34. 4.34. required_without_all:foo,bar,…
    35. 4.35. same:field
    36. 4.36. size:value
    37. 4.37. timezone
    38. 4.38. unique:table,column,except,idColumn
    39. 4.39. url
  5. 5. Условные правила
  6. 6. Собственные сообщения об ошибках
  7. 7. Собственные правила проверки

Этот перевод актуален для англоязычной документации на

04.12.2014

(ветка

4.2) ,

25.05.2014

(ветка

4.1) и

16.10.2014

(ветка

4.0).
Опечатка? Выдели и нажми Ctrl+Enter.

Основы использования

Laravel поставляется с простой, удобной системой проверки ввода и получения сообщений об ошибках — классом PHPValidation.

Простейший пример проверки ввода

PHP

$validator Validator::make(
  array(
'name' => 'Дейл'),
  array(
'name' => 'required|min:5')
);

Первый параметр, передаваемый методу PHPValidator::make() — данные для проверки. Второй параметр — правила, которые к ним должны быть применены.

Использование массивов для указания правил

Несколько правил могут быть разделены либо прямой чертой (|), либо быть отдельными элементами массива.

PHP

$validator Validator::make(
  array(
'name' => 'Дейл'),
  array(
'name' => array('required''min:5'))
);

Проверка нескольких полей

PHP

$validator Validator::make(
  array(
    
'name' => 'Дейл',
    
'password' => 'плохойпароль',
    
'email' => 'email@example.com'
  
),
  array(
    
'name' => 'required',
    
'password' => 'required|min:8',
    
'email' => 'required|email|unique:users'
  
)
);

Как только был создан экземпляр PHPValidator, метод PHPfails() (или PHPpasses()) может быть использован для проведения проверки.

PHP

if ($validator->fails()) {
  
// Переданные данные не прошли проверку.
}

Если PHPValidator нашёл ошибки, вы можете получить его сообщения таким образом:

PHP

$messages $validator->messages();

Вы также можете получить массив правил, данные которые не прошли проверку, без самих сообщений:

PHP

$failed $validator->failed();

Проверка файлов

Класс PHPValidator содержит несколько изначальных правил для проверки файлов, такие как size, mimes и другие. Для выполнения проверки над файлами просто передайте эти файлы вместе с другими данными.

Работа с сообщениями об ошибках

После вызова метода PHPValidator::messages() вы получите объект PHPMessageBag, который имеет набор полезных методов для доступа к сообщеням об ошибках.

Получение первого сообщения для поля

PHP

echo $messages->first('email');

Получение всех сообщений для одного поля

PHP

foreach ($messages->get('email') as $message) {
  
//
}

Получение всех сообщений для всех полей

PHP

foreach ($messages->all() as $message) {
  
//
}

Проверка на наличие сообщения для поля

PHP

if ($messages->has('email')) {
  
//
}

Получение ошибки в заданном формате

PHP

echo $messages->first('email''<p>:message</p>');

По умолчанию сообщения форматируются в вид, который подходит для Bootstrap.

Получение всех сообщений в заданном формате

PHP

foreach ($messages->all('<li>:message</li>') as $message) {
  
//
}

Ошибки и шаблоны

Как только вы провели проверку вам понадобиться простой способ, чтобы передать ошибки обратно в шаблон. Laravel позволяет удобно сделать это. Представьте, что у нас есть такие правила:

PHP

Route::get('register', function () {
  return 
View::make('user.register');
});
Route::post('register', function () {
  
$rules = array(...);$validator Validator::make(Input::all(), $rules);

  if (

$validator->fails()) {
    return 
Redirect::to('register')->withErrors($validator);
  }
});

Заметьте, что когда проверки не пройдены, мы передаём объект PHPValidator объекту переадресации PHPRedirect с помощью метода PHPwithErrors(). Этот метод сохранит сообщения об ошибках в одноразовых переменных сессии, таким образом делая их доступными для следующего запроса.

Однако мы не всегда должны явно передавать сообщения об ошибках в наших GET-маршрутах. Laravel проверяет данные сессии на наличие сообщений и автоматически привязывает их к шаблону, если они доступны. Таким образом, важно помнить, что переменная PHP$errors будет доступна для всех ваших шаблонов всегда, при любом запросе. Это позволяет вам считать, что переменная PHP$errors всегда определена и может безопасно использоваться. Переменная PHP$errors — экземпляр класса PHPMessageBag.

Таким образом, после переадресации вы можете прибегнуть к автоматически установленной в шаблоне переменной PHP$errors:

PHP

<?php echo $errors->first('email'); ?>


+
4.2

добавлено в

4.2

(04.12.2014)

Именованные наборы ошибок

Если у вас несколько форм на одной странице, то будет удобно определить название набора PHPMessageBag для ошибок. Это позволит вам получать сообщения об ошибках для конкретной формы. Просто передайте название в качестве второго аргумента в метод PHPwithErrors:

PHP

return Redirect::to('register')->withErrors($validator'login');

Теперь вы можете обращаться к этому экземпляру PHPMessageBag из переменной PHP$errors:

PHP

<?php echo $errors->login->first('email'); ?>

Доступные правила проверки

accepted

Поле должно быть в значении yes, on или 1. Это полезно для проверки принятия правил и лицензий.

active_url

Поле должно быть корректным URL, доступным через функцию checkdnsrr.

after:date

Поле должно быть датой, более поздней, чем date. Строки приводятся к датам функцией strtotime.

alpha

Поле должно содержать только латинские символы.

alpha_dash

Поле должно содержать только латинские символы, цифры, знаки подчёркивания (_) и дефисы (-).

alpha_num

Поле должно содержать только латинские символы и цифры.


+
4.1

добавлено в

4.1

(25.05.2014)

array

Поле должно быть массивом (тип array).

before:date

Поле должно быть датой, более ранней, чем date. Строки приводятся к датам функцией strtotime.

between:min,max

Поле должно быть числом в диапазоне от min до max. Строки, числа и файлы трактуются аналогично правилу size.


+
4.2

добавлено в

4.2

(04.12.2014)

boolean

Поле должно соответствовать логическому типу. Доступные значения: true, false, 1, 0, "1" и "0".

confirmed

Значение поля должно соответствовать значению поля с этим именем, плюс _confirmation. Например, если проверяется поле password, то на вход должно быть передано совпадающее по значению поле password_confirmation.

date

Поле должно быть правильной датой в соответствии с функцией strtotime.

date_format:format

Поле должно подходить под формату даты format в соответствии с функцией date_parse_from_format.

different:field

Значение проверяемого поля должно отличаться от значения поля field.


+
4.1

добавлено в

4.1

(25.05.2014)

digits:value

Поле должно быть числовым и иметь длину, равную value.


+
4.1

добавлено в

4.1

(25.05.2014)

digits_between:min,max

Поле должно иметь длину в диапазоне между min и max.

email

Поле должно быть корректным адресом e-mail.

exists:table,column

Поле должно существовать в заданной таблице базы данных.

Простое использование

PHP

'state' => 'exists:states'

Указание имени поля в таблице

PHP

'state' => 'exists:states,abbreviation'

Вы также можете указать больше условий, которые будут добавлены к запросу WHERE:

PHP

'email' => 'exists:staff,email,account_id,1'


+
4.1

добавлено в

4.1

(25.05.2014)

Если передать значение NULL в запрос WHERE, то это добавит проверку значения БД на совпадение с NULL:

PHP

'email' => 'exists:staff,email,deleted_at,NULL'

image

Загруженный файл должен быть изображением в формате JPEG, PNG, BMP или GIF.

in:foo,bar,…

Значение поля должно быть одним из перечисленных (foo, bar и т.д.).

integer

Поле должно иметь корректное целочисленное значение.

ip

Поле должно быть корректным IP-адресом.

max:value

Значение поля должно быть меньше или равно value. Строки, числа и файлы трактуются аналогично правилу size.

mimes:foo,bar,…

MIME-тип загруженного файла должен быть одним из перечисленных.

Простое использование

PHP

'photo' => 'mimes:jpeg,bmp,png'

min:value

Значение поля должно быть более value. Строки, числа и файлы трактуются аналогично правилу size.

not_in:foo,bar,…

Значение поля не должно быть одним из перечисленных (foo, bar и т.д.).

numeric

Поле должно иметь корректное числовое или дробное значение.

regex:pattern

Поле должно соответствовать заданному регулярному выражению.

Внимание: при использовании этого правила может быть нужно перечислять другие правила в виде элементов массива, особенно если выражение содержит символ вертикальной черты (|).

required

Проверяемое поле должно иметь непустое значение.

required_if:field,value,…

Проверяемое поле должно иметь непустое значение, если другое поле field имеет любое значение value (начиная с версии 4.2 можно передать больше одного value через запятую — прим. пер.).

required_with:foo,bar,…

Проверяемое поле должно иметь непустое значение, но только если присутствует любое из перечисленных полей (foo, bar и т.д.).


+
4.1

добавлено в

4.1

(25.05.2014)

required_with_all:foo,bar,…

Проверяемое поле должно иметь непустое значение, но только если присутствует все перечисленные поля (foo, bar и т.д.).

required_without:foo,bar,…

Проверяемое поле должно иметь непустое значение, но только если не присутствует любое из перечисленных полей (foo, bar и т.д.).


+
4.1

добавлено в

4.1

(25.05.2014)

required_without_all:foo,bar,…

Проверяемое поле должно иметь непустое значение, но только если не присутствуют все перечисленные поля (foo, bar и т.д.).

same:field

Поле должно иметь то же значение, что и поле field.

size:value

Поле должно иметь совпадающий с value размер. Для строк это обозначает длину, для чисел — число, для файлов — размер в килобайтах.


+
4.2

добавлено в

4.2

(04.12.2014)

timezone

Поле должно содержать корректный идентификатор временной зоны в соответствии с PHP-функцией PHPtimezone_identifiers_list.

unique:table,column,except,idColumn

Значение поля должно быть уникальным в заданной таблице базы данных. Если column не указано, то будет использовано имя поля.

Простое использование

PHP

'email' => 'unique:users'

Указание имени поля в таблице

PHP

'email' => 'unique:users,email_address'

Игнорирование определённого ID

PHP

'email' => 'unique:users,email_address,10'

Добавление дополнительных условий

Вы также можете указать больше условий, которые будут добавлены к запросу WHERE:

PHP

'email' => 'unique:users,email_address,NULL,id,account_id,1'

В правиле выше только строки с account_id равном 1 будут включены в проверку.

url

Поле должно быть корректным URL.

Эта функция использует PHP-метод PHPfilter_var().

Условные правила


+
4.1

добавлено в

4.1

(25.05.2014)

В некоторых случаях вам нужно запускать проверки поля, только если оно есть во входном массиве. Чтобы быстро это сделать, добавьте правило sometimes в ваш список правил:

PHP

$v Validator::make($data, array(
  
'email' => 'sometimes|required|email',
));

В этом примере поле email будет проверено, только если оно есть в массиве $data.

Сложные условные проверки

Иногда вам может быть нужно, чтобы поле имело какое-либо значение только если другое поле имеет значение, скажем, больше 100. Или вы можете требовать наличия двух полей только, когда также указано третье. Это легко достигается условными правилами. Сперва создайте объект PHPValidator с набором статичных правил, которые никогда не изменяются:

PHP

$v Validator::make($data, array(
  
'email' => 'required|email',
  
'games' => 'required|numeric',
));

Теперь предположим, что ваше приложения написано для коллекционеров игр. Если регистрируется коллекционер с более, чем 100 играми, то мы хотим их спросить, зачем им такое количество. Например, у них может быть магазин или может им просто нравится их собирать. Итак, для добавления такого условного правила мы используем метод PHPValidator::sometimes():

PHP

$v->sometimes('reason''required|max:500', function ($input) {
  return 
$input->games >= 100;
});

Первый параметр этого метода — имя поля, которое мы проверяем. Второй параметр — правило, которое мы хотим добавить, если переданная функция-замыкание (третий параметр) вернёт PHPtrue. Этот метод позволяет легко создавать сложные правила проверки ввода. Вы можете даже добавлять одни и те же условные правила для нескольких полей одновременно:

PHP

$v->sometimes(array('reason''cost'), 'required', function ($input) {
  return 
$input->games >= 100;
});

Параметр PHP$input, передаваемый замыканию — объект PHPIlluminateSupportFluent и может использоваться для чтения проверяемого ввода и файлов.

Собственные сообщения об ошибках

Вы можете передать собственные сообщения об ошибках вместо используемых по умолчанию. Есть несколько способов это сделать.

Передача своих сообщений в PHPValidator

PHP

$messages = array(
  
'required' => 'Поле :attribute должно быть заполнено.',
);
$validator Validator::make($input$rules$messages);

Строка :attribute будет заменена на имя проверяемого поля. Вы также можете использовать и другие строки-переменные.

Использование других переменных-строк

PHP

$messages = array(
  
'same'    => 'Значения :attribute и :other должны совпадать.',
  
'size'    => 'Поле :attribute должно быть ровно exactly :size.',
  
'between' => 'Значение :attribute должно быть от :min и до :max.',
  
'in'      => 'Поле :attribute должно иметь одно из следующих значений: :values',
);

Указание собственного сообщения для отдельного поля

Иногда вам может потребоваться указать своё сообщение для отдельного поля:

PHP

$messages = array(
  
'email.required' => 'Нам нужно знать ваш e-mail адрес!',
);

Указание собственных сообщений в языковом файле

Может быть также полезно определять эти сообщения в языковом файле вместо того, чтобы передавать их в PHPValidator напрямую. Для этого добавьте сообщения в массив custom языкового файла app/lang/xx/validation.php.

PHP

'custom' => array(
  
'email' => array(
    
'required' => 'Нам нужно знать ваш e-mail адрес!',
  ),
),

Собственные правила проверки

Регистрация собственного правила

Laravel изначально содержит множество полезных правил, однако вам может понадобиться создать собственные. Одним из способов зарегистрировать произвольное правило — через метод PHPValidator::extend():

PHP

Validator::extend('foo', function ($attribute$value$parameters) {
  return 
$value == 'foo';
});

Переданная функция-замыкание получает три параметра: имя проверяемого поля PHP$attribute, значение поля PHP$value и массив параметров PHP$parameters, переданных правилу.

Вместо замыкания в метод PHPextend() также можно передать ссылку на метод класса:

PHP

Validator::extend('foo''FooValidator@validate');

Обратите внимание, что вам также понадобиться определить сообщение об ошибке для нового правила. Вы можете сделать это либо передавая его в виде массива строк в PHPValidator, либо вписав в языковой файл.

Расширение класса PHPValidator

Вместо использования функций-замыканий для расширения набора доступных правил вы можете расширить сам класс PHPValidator. Для этого создайте класс, который наследует PHPIlluminateValidationValidator. Вы можете добавить новые методы проверок, начав их имя с validate:

PHP

<?phpclass CustomValidator extends IlluminateValidationValidator {

    public function 

validateFoo($attribute$value$parameters)
    {
      return 
$value == 'значение';
    }

  }

Регистрация нового класса PHPValidator

Затем вам нужно зарегистрировать собственное расширение:

PHP

Validator::resolver(function ($translator$data$rules$messages) {
  return new 
CustomValidator($translator$data$rules$messages);
});

Иногда при создании своего класса вам может понадобиться определить собственные строки-переменные для замены в сообщениях об ошибках. Это делается путём создания класса, как было описано выше, и добавлением функций с именами вида PHPreplaceXXX().

PHP

protected function replaceFoo ($message$attribute$rule$parameters) {
  return 
str_replace(':foo'$parameters[0], $message);
}


+
4.1

добавлено в

4.1

(25.05.2014)

Если вы хотите добавить собственный «заменитель» сообщений без наследования класса PHPValidator, используйте метод PHPValidator::replacer():

PHP

Validator::replacer('rule', function($message$attribute$rule$parameters)
{
  
//
});
  • Basic Usage
  • Controller Validation
  • Form Request Validation
  • Working With Error Messages
  • Error Messages & Views
  • Available Validation Rules
  • Conditionally Adding Rules
  • Custom Error Messages
  • Custom Validation Rules

Basic Usage

Laravel ships with a simple, convenient facility for validating data and retrieving validation error messages via the Validation class.

Basic Validation Example

$validator = Validator::make(
    ['name' => 'Dayle'],
    ['name' => 'required|min:5']
);

The first argument passed to the make method is the data under validation. The second argument is the validation rules that should be applied to the data.

Using Arrays To Specify Rules

Multiple rules may be delimited using either a «pipe» character, or as separate elements of an array.

$validator = Validator::make(
    ['name' => 'Dayle'],
    ['name' => ['required', 'min:5']]
);

Validating Multiple Fields

$validator = Validator::make(
    [
        'name' => 'Dayle',
        'password' => 'lamepassword',
        'email' => 'email@example.com'
    ],
    [
        'name' => 'required',
        'password' => 'required|min:8',
        'email' => 'required|email|unique:users'
    ]
);

Once a Validator instance has been created, the fails (or passes) method may be used to perform the validation.

if ($validator->fails())
{
    // The given data did not pass validation
}

If validation has failed, you may retrieve the error messages from the validator.

$messages = $validator->messages();

You may also access an array of the failed validation rules, without messages. To do so, use the failed method:

$failed = $validator->failed();

Validating Files

The Validator class provides several rules for validating files, such as size, mimes, and others. When validating files, you may simply pass them into the validator with your other data.

After Validation Hook

The validator also allows you to attach callbacks to be run after validation is completed. This allows you to easily perform further validation, and even add more error messages to the message collection. To get started, use the after method on a validator instance:

$validator = Validator::make(...);

$validator->after(function($validator)
{
    if ($this->somethingElseIsInvalid())
    {
        $validator->errors()->add('field', 'Something is wrong with this field!');
    }
});

if ($validator->fails())
{
    //
}

You may add as many after callbacks to a validator as needed.

Controller Validation

Of course, manually creating and checking a Validator instance each time you do validation is a headache. Don’t worry, you have other options! The base AppHttpControllersController class included with Laravel uses a ValidatesRequests trait. This trait provides a single, convenient method for validating incoming HTTP requests. Here’s what it looks like:

/**
 * Store the incoming blog post.
 *
 * @param  Request  $request
 * @return Response
 */
public function store(Request $request)
{
    $this->validate($request, [
        'title' => 'required|unique|max:255',
        'body' => 'required',
    ]);

    //
}

If validation passes, your code will keep executing normally. However, if validation fails, an IlluminateContractsValidationValidationException will be thrown. This exception is automatically caught and a redirect is generated to the user’s previous location. The validation errors are even automatically flashed to the session!

If the incoming request was an AJAX request, no redirect will be generated. Instead, an HTTP response with a 422 status code will be returned to the browser containing a JSON representation of the validation errors.

For example, here is the equivalent code written manually:

/**
 * Store the incoming blog post.
 *
 * @param  Request  $request
 * @return Response
 */
public function store(Request $request)
{
    $v = Validator::make($request->all(), [
        'title' => 'required|unique|max:255',
        'body' => 'required',
    ]);

    if ($v->fails())
    {
        return redirect()->back()->withErrors($v->errors());
    }

    //
}

Customizing The Flashed Error Format

If you wish to customize the format of the validation errors that are flashed to the session when validation fails, override the formatValidationErrors on your base controller. Don’t forget to import the IlluminateValidationValidator class at the top of the file:

/**
 * {@inheritdoc}
 */
protected function formatValidationErrors(Validator $validator)
{
    return $validator->errors()->all();
}

Form Request Validation

For more complex validation scenarios, you may wish to create a «form request». Form requests are custom request classes that contain validation logic. To create a form request class, use the make:request Artisan CLI command:

php artisan make:request StoreBlogPostRequest

The generated class will be placed in the app/Http/Requests directory. Let’s add a few validation rules to the rules method:

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    return [
        'title' => 'required|unique|max:255',
        'body' => 'required',
    ];
}

So, how are the validation rules executed? All you need to do is type-hint the request on your controller method:

/**
 * Store the incoming blog post.
 *
 * @param  StoreBlogPostRequest  $request
 * @return Response
 */
public function store(StoreBlogPostRequest $request)
{
    // The incoming request is valid...
}

The incoming form request is validated before the controller method is called, meaning you do not need to clutter your controller with any validation logic. It has already been validated!

If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an AJAX request, a HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.

Authorizing Form Requests

The form request class also contains an authorize method. Within this method, you may check if the authenticated user actually has the authority to update a given resource. For example, if a user is attempting to update a blog post comment, do they actually own that comment? For example:

/**
 * Determine if the user is authorized to make this request.
 *
 * @return bool
 */
public function authorize()
{
    $commentId = $this->route('comment');

    return Comment::where('id', $commentId)
                  ->where('user_id', Auth::id())->exists();
}

Note the call to the route method in the example above. This method grants you access to the URI parameters defined on the route being called, such as the {comment} parameter in the example below:

Route::post('comment/{comment}');

If the authorize method returns false, a HTTP response with a 403 status code will automatically be returned and your controller method will not execute.

If you plan to have authorization logic in another part of your application, simply return true from the authorize method:

/**
 * Determine if the user is authorized to make this request.
 *
 * @return bool
 */
public function authorize()
{
    return true;
}

Customizing The Flashed Error Format

If you wish to customize the format of the validation errors that are flashed to the session when validation fails, override the formatErrors on your base request (AppHttpRequestsRequest). Don’t forget to import the IlluminateValidationValidator class at the top of the file:

/**
 * {@inheritdoc}
 */
protected function formatErrors(Validator $validator)
{
    return $validator->errors()->all();
}

Working With Error Messages

After calling the messages method on a Validator instance, you will receive a MessageBag instance, which has a variety of convenient methods for working with error messages.

Retrieving The First Error Message For A Field

echo $messages->first('email');

Retrieving All Error Messages For A Field

foreach ($messages->get('email') as $message)
{
    //
}

Retrieving All Error Messages For All Fields

foreach ($messages->all() as $message)
{
    //
}

Determining If Messages Exist For A Field

if ($messages->has('email'))
{
    //
}

Retrieving An Error Message With A Format

echo $messages->first('email', '<p>:message</p>');

Note: By default, messages are formatted using Bootstrap compatible syntax.

Retrieving All Error Messages With A Format

foreach ($messages->all('<li>:message</li>') as $message)
{
    //
}

Error Messages & Views

Once you have performed validation, you will need an easy way to get the error messages back to your views. This is conveniently handled by Laravel. Consider the following routes as an example:

Route::get('register', function()
{
    return View::make('user.register');
});

Route::post('register', function()
{
    $rules = [...];

    $validator = Validator::make(Input::all(), $rules);

    if ($validator->fails())
    {
        return redirect('register')->withErrors($validator);
    }
});

Note that when validation fails, we pass the Validator instance to the Redirect using the withErrors method. This method will flash the error messages to the session so that they are available on the next request.

However, notice that we do not have to explicitly bind the error messages to the view in our GET route. This is because Laravel will always check for errors in the session data, and automatically bind them to the view if they are available. So, it is important to note that an $errors variable will always be available in all of your views, on every request, allowing you to conveniently assume the $errors variable is always defined and can be safely used. The $errors variable will be an instance of MessageBag.

So, after redirection, you may utilize the automatically bound $errors variable in your view:

<?php echo $errors->first('email'); ?>

Named Error Bags

If you have multiple forms on a single page, you may wish to name the MessageBag of errors. This will allow you to retrieve the error messages for a specific form. Simply pass a name as the second argument to withErrors:

return redirect('register')->withErrors($validator, 'login');

You may then access the named MessageBag instance from the $errors variable:

<?php echo $errors->login->first('email'); ?>

Available Validation Rules

Below is a list of all available validation rules and their function:

  • Accepted
  • Active URL
  • After (Date)
  • Alpha
  • Alpha Dash
  • Alpha Numeric
  • Array
  • Before (Date)
  • Between
  • Boolean
  • Confirmed
  • Date
  • Date Format
  • Different
  • Digits
  • Digits Between
  • E-Mail
  • Exists (Database)
  • Image (File)
  • In
  • Integer
  • IP Address
  • Max
  • MIME Types
  • Min
  • Not In
  • Numeric
  • Regular Expression
  • Required
  • Required If
  • Required With
  • Required With All
  • Required Without
  • Required Without All
  • Same
  • Size
  • String
  • Timezone
  • Unique (Database)
  • URL

accepted

The field under validation must be yes, on, 1, or true. This is useful for validating «Terms of Service» acceptance.

active_url

The field under validation must be a valid URL according to the checkdnsrr PHP function.

after:date

The field under validation must be a value after a given date. The dates will be passed into the PHP strtotime function.

alpha

The field under validation must be entirely alphabetic characters.

alpha_dash

The field under validation may have alpha-numeric characters, as well as dashes and underscores.

alpha_num

The field under validation must be entirely alpha-numeric characters.

array

The field under validation must be of type array.

before:date

The field under validation must be a value preceding the given date. The dates will be passed into the PHP strtotime function.

between:min,max

The field under validation must have a size between the given min and max. Strings, numerics, and files are evaluated in the same fashion as the size rule.

boolean

The field under validation must be able to be cast as a boolean. Accepted input are true, false, 1, 0, "1" and "0".

confirmed

The field under validation must have a matching field of foo_confirmation. For example, if the field under validation is password, a matching password_confirmation field must be present in the input.

date

The field under validation must be a valid date according to the strtotime PHP function.

date_format:format

The field under validation must match the format defined according to the date_parse_from_format PHP function.

different:field

The given field must be different than the field under validation.

digits:value

The field under validation must be numeric and must have an exact length of value.

digits_between:min,max

The field under validation must have a length between the given min and max.

email

The field under validation must be formatted as an e-mail address.

exists:table,column

The field under validation must exist on a given database table.

Basic Usage Of Exists Rule

'state' => 'exists:states'

Specifying A Custom Column Name

'state' => 'exists:states,abbreviation'

You may also specify more conditions that will be added as «where» clauses to the query:

'email' => 'exists:staff,email,account_id,1'

Passing NULL as a «where» clause value will add a check for a NULL database value:

'email' => 'exists:staff,email,deleted_at,NULL'

image

The file under validation must be an image (jpeg, png, bmp, gif, or svg)

in:foo,bar,…

The field under validation must be included in the given list of values.

integer

The field under validation must have an integer value.

ip

The field under validation must be formatted as an IP address.

max:value

The field under validation must be less than or equal to a maximum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.

mimes:foo,bar,…

The file under validation must have a MIME type corresponding to one of the listed extensions.

Basic Usage Of MIME Rule

'photo' => 'mimes:jpeg,bmp,png'

min:value

The field under validation must have a minimum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.

not_in:foo,bar,…

The field under validation must not be included in the given list of values.

numeric

The field under validation must have a numeric value.

regex:pattern

The field under validation must match the given regular expression.

Note: When using the regex pattern, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character.

required

The field under validation must be present in the input data.

required_if:field,value,…

The field under validation must be present if the field field is equal to any value.

required_with:foo,bar,…

The field under validation must be present only if any of the other specified fields are present.

required_with_all:foo,bar,…

The field under validation must be present only if all of the other specified fields are present.

required_without:foo,bar,…

The field under validation must be present only when any of the other specified fields are not present.

required_without_all:foo,bar,…

The field under validation must be present only when all of the other specified fields are not present.

same:field

The given field must match the field under validation.

size:value

The field under validation must have a size matching the given value. For string data, value corresponds to the number of characters. For numeric data, value corresponds to a given integer value. For files, size corresponds to the file size in kilobytes.

string:value

The field under validation must be a string type.

timezone

The field under validation must be a valid timezone identifier according to the timezone_identifiers_list PHP function.

unique:table,column,except,idColumn

The field under validation must be unique on a given database table. If the column option is not specified, the field name will be used.

Occasionally, you may need to set a custom connection for database queries made by the Validator. As seen above, setting unique:users as a validation rule will use the default database connection to query the database. To override this, do the following:

$verifier = App::make('validation.presence');

$verifier->setConnection('connectionName');

$validator = Validator::make($input, [
    'name' => 'required',
    'password' => 'required|min:8',
    'email' => 'required|email|unique:users',
]);

$validator->setPresenceVerifier($verifier);

Basic Usage Of Unique Rule

'email' => 'unique:users'

Specifying A Custom Column Name

'email' => 'unique:users,email_address'

Forcing A Unique Rule To Ignore A Given ID

'email' => 'unique:users,email_address,10'

Adding Additional Where Clauses

You may also specify more conditions that will be added as «where» clauses to the query:

'email' => 'unique:users,email_address,NULL,id,account_id,1'

In the rule above, only rows with an account_id of 1 would be included in the unique check.

url

The field under validation must be formatted as an URL.

Note: This function uses PHP’s filter_var method.

Conditionally Adding Rules

In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule to your rule list:

$v = Validator::make($data, [
    'email' => 'sometimes|required|email',
]);

In the example above, the email field will only be validated if it is present in the $data array.

Complex Conditional Validation

Sometimes you may wish to require a given field only if another field has a greater value than 100. Or you may need two fields to have a given value only when another field is present. Adding these validation rules doesn’t have to be a pain. First, create a Validator instance with your static rules that never change:

$v = Validator::make($data, [
    'email' => 'required|email',
    'games' => 'required|numeric',
]);

Let’s assume our web application is for game collectors. If a game collector registers with our application and they own more than 100 games, we want them to explain why they own so many games. For example, perhaps they run a game re-sell shop, or maybe they just enjoy collecting. To conditionally add this requirement, we can use the sometimes method on the Validator instance.

$v->sometimes('reason', 'required|max:500', function($input)
{
    return $input->games >= 100;
});

The first argument passed to the sometimes method is the name of the field we are conditionally validating. The second argument is the rules we want to add. If the Closure passed as the third argument returns true, the rules will be added. This method makes it a breeze to build complex conditional validations. You may even add conditional validations for several fields at once:

$v->sometimes(['reason', 'cost'], 'required', function($input)
{
    return $input->games >= 100;
});

Note: The $input parameter passed to your Closure will be an instance of IlluminateSupportFluent and may be used as an object to access your input and files.

Custom Error Messages

If needed, you may use custom error messages for validation instead of the defaults. There are several ways to specify custom messages.

Passing Custom Messages Into Validator

$messages = [
    'required' => 'The :attribute field is required.',
];

$validator = Validator::make($input, $rules, $messages);

Note: The :attribute place-holder will be replaced by the actual name of the field under validation. You may also utilize other place-holders in validation messages.

Other Validation Place-Holders

$messages = [
    'same'    => 'The :attribute and :other must match.',
    'size'    => 'The :attribute must be exactly :size.',
    'between' => 'The :attribute must be between :min - :max.',
    'in'      => 'The :attribute must be one of the following types: :values',
];

Specifying A Custom Message For A Given Attribute

Sometimes you may wish to specify a custom error messages only for a specific field:

$messages = [
    'email.required' => 'We need to know your e-mail address!',
];

Specifying Custom Messages In Language Files

In some cases, you may wish to specify your custom messages in a language file instead of passing them directly to the Validator. To do so, add your messages to custom array in the resources/lang/xx/validation.php language file.

'custom' => [
    'email' => [
        'required' => 'We need to know your e-mail address!',
    ],
],

Custom Validation Rules

Registering A Custom Validation Rule

Laravel provides a variety of helpful validation rules; however, you may wish to specify some of your own. One method of registering custom validation rules is using the Validator::extend method:

Validator::extend('foo', function($attribute, $value, $parameters)
{
    return $value == 'foo';
});

The custom validator Closure receives three arguments: the name of the $attribute being validated, the $value of the attribute, and an array of $parameters passed to the rule.

You may also pass a class and method to the extend method instead of a Closure:

Validator::extend('foo', 'FooValidator@validate');

Note that you will also need to define an error message for your custom rules. You can do so either using an inline custom message array or by adding an entry in the validation language file.

Extending The Validator Class

Instead of using Closure callbacks to extend the Validator, you may also extend the Validator class itself. To do so, write a Validator class that extends IlluminateValidationValidator. You may add validation methods to the class by prefixing them with validate:

<?php

class CustomValidator extends IlluminateValidationValidator {

    public function validateFoo($attribute, $value, $parameters)
    {
        return $value == 'foo';
    }

}

Registering A Custom Validator Resolver

Next, you need to register your custom Validator extension:

Validator::resolver(function($translator, $data, $rules, $messages)
{
    return new CustomValidator($translator, $data, $rules, $messages);
});

When creating a custom validation rule, you may sometimes need to define custom place-holder replacements for error messages. You may do so by creating a custom Validator as described above, and adding a replaceXXX function to the validator.

protected function replaceFoo($message, $attribute, $rule, $parameters)
{
    return str_replace(':foo', $parameters[0], $message);
}

If you would like to add a custom message «replacer» without extending the Validator class, you may use the Validator::replacer method:

Validator::replacer('rule', function($message, $attribute, $rule, $parameters)
{
    //
});

Краткий пример

Пример валидации формы и вывод сообщений об ошибках для пользователя.

Определение роутов

Создадим роуты в файле routes/web.php:

Route::get('post/create', 'PostController@create');

Route::post('post', 'PostController@store');

Роут GET отображает форму для создания нового поста в блоге, POST будет сохранять новую запись в базе данных.

Создание контроллера

Контроллер, который обрабатывает эти роуты. Метод store пока остался пустым:

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppHttpControllersController;

class PostController extends Controller
{
    /**
     * Показать форму для создания новой записи в блоге.
     *
     * @return Response
     */
    public function create()
    {
        return view('post.create');
    }

    /**
     * Хранить новую запись в блоге.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        // Validate and store the blog post...
    }
}

Написание логики валидации

Заполняем метод store валидацией при создания нового поста. Если проанализировать базовый контроллер (AppHttpControllersController), видно, что он включает в себя трейт ValidatesRequests, который обеспечивает все контроллеры удобным методом validate.

Метод validate принимает два параметра экземпляр HTTP запроса и правила валидации. Если все правила не нарушены, код будет выполняться далее. Однако, если проверка не пройдена, будет выброшено исключение и сообщение об ошибке автоматически отправится обратно пользователю. В HTTP запросе ответ будет перенаправлен обратно с заполненными flash-переменными, в то время как на AJAX запрос отправится JSON.

Для понимания метода validate, пример store:

/**
 * Store a new blog post.
 *
 * @param  Request  $request
 * @return Response
 */
public function store(Request $request)
{
    $this->validate($request, [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);

    // The blog post is valid, store in database...
}

Остановка после первой неудачной проверки

Если нужно остановить выполнение остальных правил после первой неудачной проверки. Для этого используется атрибут bail:

$this->validate($request, [
    'title' => 'bail|unique:posts|max:255',
    'body' => 'required',
]);

В этом примере, если для атрибута title не выполняется правило required, следующие правило unique проверяться не будет.

Проверка вложенных атрибутах (массив)

Если данные HTTP запроса содержат «вложенные» параметры, можно указать их, используя синтаксис с точкой:

$this->validate($request, [
    'title' => 'required|unique:posts|max:255',
    'author.name' => 'required',
    'author.description' => 'required',
]);

Отображение ошибок валидации

В примере пользователь будет перенаправлен в метод create контроллера и можно отобразить сообщения об ошибках в шаблоне:

<!-- /resources/views/post/create.blade.php -->

<h1>Create Post</h1>

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

<!-- Create Post Form -->

Дополнительные поля

По умолчанию в Laravel включены глобальные посредники TrimStrings и mptConvertEyStringsToNull. Они перечислены в свойстве $middleware класса AppHttpKernel. Из-за этого нужно часто помечать дополнительные поля как nullable, если не нужно, чтобы валидатор считал не действительным значение null. Например:

$this->validate($request, [
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
    'publish_at' => 'nullable|date',
]);

В этом примере указано что поле publish_at может быть null или должно содержать дату. Если модификатор nullable не добавляется в правило, проверяющий элемент будет рассматривать null как недопустимую дату.

Настройка формата вывода ошибок валидации

Для настройки вывода ошибок валидации, которые будут во flash-переменных после нарушений правил, нужно переопределить метод formatValidationErrors в базовом контроллере и подключить класс IlluminateContractsValidationValidator:

<?php

namespace AppHttpControllers;

use IlluminateFoundationBusDispatchesJobs;
use IlluminateContractsValidationValidator;
use IlluminateRoutingController as BaseController;
use IlluminateFoundationValidationValidatesRequests;

abstract class Controller extends BaseController
{
    use DispatchesJobs, ValidatesRequests;

    /**
     * {@inheritdoc}
     */
    protected function formatValidationErrors(Validator $validator)
    {
        return $validator->errors()->all();
    }
}

AJAX запросы и валидация

При использовании метода validate во время запроса AJAX, Laravel не будет генерировать ответ с перенаправлением. Вместо этого Laravel генерирует ответ с JSON данными, содержащий в себе все ошибки проверки. Этот ответ будет отправлен с кодом состояния HTTP 422.

Валидация form request

Создание Form Request

# php artisan make:request StoreBlogPost

Сгенерированный класс будет размещен в каталоге app/Http/Requests

Для проверки используется метод rules:

/**
 * Получить правила валидации, применимые к запросу.
 *
 * @return array
 */
public function rules()
{
    return [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ];
}

Для проверки валидации необходимо в методе контроллера для входящей переменной указать класс как тип переменной

/**
 * Store the incoming blog post.
 *
 * @param  StoreBlogPost  $request
 * @return Response
 */
public function store(StoreBlogPost $request)
{
    // The incoming request is valid...
}

Если проверка не пройдена, то при традиционном запросе ошибки будут записываться в сессию и будут доступны в шаблонах, иначе, если запрос был AJAX, HTTP-ответ с кодом 422 будет возвращен пользователю, включая JSON с ошибками валидации.

Добавление хуков в Form Request

Если необходимо добавить хук «after» в Form Requests, можно использовать метод withValidator. Этот метод получает полностью сформированный валидатор, позволяя вызвать любой из его методов, прежде чем фактически применяются правила:

/**
 * Настройка экземпляра валидатора.
 *
 * @param  IlluminateValidationValidator  $validator
 * @return void
 */
public function withValidator($validator)
{
    $validator->after(function ($validator) {
        if ($this->somethingElseIsInvalid()) {
            $validator->errors()->add('field', 'Something is wrong with this field!');
        }
    });
}

Авторизация Form Request

Класс Form Request содержит в себе метод authorize. В этом методе можно проверить, имеет ли аутентифицированный пользователь права на выполнение данного запроса. Например, можно проверить, есть ли у пользователя право для добавления комментариев в блог:

/**
 * Определить авторизован ли пользователь делать такой запрос.
 *
 * @return bool
 */
public function authorize()
{
    $comment = Comment::find($this->route('comment'));

    return $comment && $this->user()->can('update', $comment);
}

Form Request расширяет базовый класс Request, и можно использовать метод user, чтобы получить доступ к текущему пользователю. Вызов метода route предоставляет доступ к параметрам URI, определенным в роуте (в приведенном ниже примере это {comment}):

Route::post('comment/{comment}');

Если метод authorize возвращает false, автоматически генерируется ответ с кодом 403 и метод контроллера не выполняется.

Если же логика авторизации организована в другом месте приложения, просто достаточно вернуть true из метода authorize:

/**
 * Определить авторизован ли пользователь делать такой запрос.
 *
 * @return bool
 */
public function authorize()
{
    return true;
}

Настройка формата вывода ошибок

Если нужно настроить формат вывода ошибок валидации, которые будут заполнять flash-переменные при неудачном выполнении, необходимо переопредилить метод formatErrors в базовом request (AppHttpRequestsRequest). Должен быт подключен класс IlluminateContractsValidationValidator:

/**
 * {@inheritdoc}
 */
protected function formatErrors(Validator $validator)
{
    return $validator->errors()->all();
}

Настройка сообщений об ошибках

Для кастомизации сообщений об ошибках, используется в form request метод messages. Этот метод должен возвращать массив атрибутов/правил и их соответствующие сообщения об ошибках:

/**
 * Get the error messages for the defined validation rules.
 *
 * @return array
 */
public function messages()
{
    return [
        'title.required' => 'A title is required',
        'body.required'  => 'A message is required',
    ];
}

Создание валидаторов вручную

<?php

namespace AppHttpControllers;

use Validator;
use IlluminateHttpRequest;
use AppHttpControllersController;

class PostController extends Controller
{
    /**
     * Store a new blog post.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
        ]);

        if ($validator->fails()) {
            return redirect('post/create')
                        ->withErrors($validator)
                        ->withInput();
        }

        // Store the blog post...
    }
}

Первый аргумент, передаваемый в метод make, получает данные для проверки. Вторым аргументом идут правилами проверки, которые должны применяться к данным.

После проверки, если валидация не будет пройдена, можно использовать метод withErrors для загрузки ошибок во flash-переменные. При использовании этого метода переменная $errors будет автоматически передаваться в макеты, после перенаправления, что позволяет легко отображать данные пользователю. Метод withErrors принимает экземпляр валидатора и MessageBag или простой массив.

Автоматическое перенаправление

Validator::make($request->all(), [
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
])->validate();

MessageBag

Если есть несколько форм на одной страницы, которые необходимо провалидировать, понадобится MessageBag — он позволяет получать сообщения об ошибках для определенной формы. Нужно передайть имя в качестве второго аргумента withErrors:

return redirect('register')
            ->withErrors($validator, 'login');

Затем можно получить доступ к именованному экземпляру MessageBag из переменной $errors:

{{ $errors->login->first('email') }}

Хук после валидации

Валидатор также позволяет использовать функции обратного вызова после завершения всех проверок. Это позволяет легко выполнять дальнейшие проверки и даже добавить больше сообщений об ошибках в коллекции сообщений. Для начала работы нужно использовать метод after в экземпляре валидатора:

$validator = Validator::make(...);

$validator->after(function ($validator) {
    if ($this->somethingElseIsInvalid()) {
        $validator->errors()->add('field', 'Something is wrong with this field!');
    }
});

if ($validator->fails()) {
    //
}

Работа с сообщениями об ошибках

После вызова метода errors в экземпляре валидатора, получаем экземпляр IlluminateSupportMessageBag, который имеет целый ряд удобных методов для работы с сообщениями об ошибках. Переменная $errors, которая автоматически становится доступной для всех макетов, также является экземпляром класса MessageBag.

Извлечение первого для поля сообщения об ошибке

$errors = $validator->errors();

echo $errors->first('email');

Извлечение всех сообщений об ошибках для одного поля

foreach ($errors->get('email') as $message) {
    //
}

Если выполняется проверка поля формы с массивом, можно получить все сообщения для каждого из элементов массива с помощью символа *:

foreach ($errors->get('attachments.*') as $message) {
    //
}

Получение всех сообщений об ошибках для всех полей

foreach ($errors->all() as $message) {
    //
}

Определить наличие сообщения для определенного поля

if ($errors->has('email')) {
    //
}

Пользовательские сообщения об ошибках

При необходимости, можно использовать свои сообщения об ошибках вместо значений по умолчанию. Существует несколько способов для указания кастомных сообщений. Можно передать сообщения в качестве третьего аргумента в метод Validator::make:

$messages = [
    'required' => 'The :attribute field is required.',
];

$validator = Validator::make($input, $rules, $messages);

В этом примере :attributeбудет заменен на имя проверяемого поля. Можено использовать и другие строки-переменные. Пример:

$messages = [
    'same'    => 'The :attribute and :other must match.',
    'size'    => 'The :attribute must be exactly :size.',
    'between' => 'The :attribute must be between :min - :max.',
    'in'      => 'The :attribute must be one of the following types: :values',
];

Указание пользовательского сообщения для заданного атрибута

$messages = [
    'email.required' => 'We need to know your e-mail address!',
];

Указание собственных сообщений в файлах локализации

Также можно определять сообщения в файле локализации вместо того, чтобы передавать их в валидатор напрямую. Для этого нужно добавить сообщения в массив custom файла локализации resources/lang/xx/validation.php.

'custom' => [
    'email' => [
        'required' => 'We need to know your e-mail address!',
    ],
],

Указание пользовательских атрибутов в файлах локализации

Если необходимо, чтобы :attribute был заменен на кастомное имя, можно указать в массиве attributes файле локализации resources/lang/xx/validation.php:

'attributes' => [
    'email' => 'email address',
],

Доступные правила валидации

accepted — поле должно быть в значении yes, on или 1. Это полезно для проверки принятия правил и лицензий.

active_url — поле должно иметь действительную A или AAAA DNS-запись согласно функции PHP dns_get_record.

after:date — поле проверки должно быть после date. Строки приводятся к датам функцией strtotime:

'start_date' => 'required|date|after:tomorrow'

Вместо того чтобы приводить строки к датам, вы можете указать другое поле для сравнения даты:

'finish_date' => 'required|date|after:start_date'

after_or_equal:date — поле проверки должно быть после или равно date. Для получения дополнительной информации смотрите правило after

alpha — поле должно содержать только алфавитные символы.

alpha_dash — поле можно содержать только алфавитные символы, цифры, знаки подчёркивания _ и дефисы -.

alpha_num — поле можно содержать только алфавитные символы и цифры.

array — поле должно быть PHP-массивом.

before:date — поле должно быть датой более ранней, чем заданная дата. Строки приводятся к датам функцией strtotime.

before_or_equal:date — поле должно быть более ранней или равной заданной дате. Строки приводятся к датам функцией strtotime.

between:min,max — поле должно быть числом в диапазоне от min до max. Размеры строк, чисел и файлов трактуются аналогично правилу size.

boolean — поле должно быть логическим (булевым). Разрешенные значения: true, false, 1, 0, «1», и «0».

confirmed — значение поля должно соответствовать значению поля с этим именем, плюс foo_confirmation. Например, если проверяется поле password, то на вход должно быть передано совпадающее по значению поле password_confirmation.

date — поле должно быть правильной датой в соответствии с PHP функцией strtotime.

date_format:format — поле должно соответствовать заданному формату. Необходимо использовать функцию date или date_format при проверке поля, но не обе.

different:field — значение проверяемого поля должно отличаться от значения поля field.

digits:value — поле должно быть числовым и иметь точную длину значения.

digits_between:min,max — длина значения поля проверки должна быть между min и max.

dimensions — файл изображения должен иметь ограничения согласно параметрам:

'avatar' => 'dimensions:min_width=100,min_height=200'

Доступные ограничения: _min_width_, _max_width_, _min_height_, _max_height_, width, height, ratio.
Ограничение ratio должно быть представлено как ширина к высоте. Это может быть обыкновенная (3/2) или десятичная (1.5) дробь:

'avatar' => 'dimensions:ratio=3/2'

Поскольку это правило требует несколько аргументов, вы можете использовать метод Rule::dimensions:

use IlluminateValidationRule;

Validator::make($data, [
    'avatar' => [
        'required',
        Rule::dimensions()->maxWidth(1000)->maxHeight(500)->ratio(3 / 2),
    ],
]);

distinct — при работе с массивами, поле не должно иметь повторяющихся значений.

'foo.*.id' => 'distinct'

email — поле должно быть корректным адресом e-mail.

exists:table,column — поле должно существовать в указанной таблице базы данных.
базовое использование правила Exists

'state' => 'exists:states'

указание пользовательского названия столбца

'state' => 'exists:states,abbreviation'

Иногда может потребоваться подключение к базе данных и использование в запросе exists, этого можно добиться путем добавления к соединению название таблицы, используя синтаксис с точкой:

'email' => 'exists:connection.staff,email'

Если бы вы хотите модифицировать запрос, можно использовать класс Rule, в данном примере мы будем использовать массив вместо знака |:

use IlluminateValidationRule;

Validator::make($data, [
    'email' => [
        'required',
        Rule::exists('staff')->where(function ($query) {
            $query->where('account_id', 1);
        }),
    ],
]);

file — поле должно быть успешно загруженным файлом.

filled — поле не должно быть пустым.

image — загруженный файл должен быть в формате jpeg, png, bmp, gif или svg.

in:foo,bar,… -значение поля должно быть одним из перечисленных. Поскольку это правило иногда вынуждает вас использовать функцию implode, для этого случая есть метод Rule::in:

use IlluminateValidationRule;

Validator::make($data, [
    'zones' => [
        'required',
        Rule::in(['first-zone', 'second-zone']),
    ],
]);

in_array:anotherfield — в массиве должны существовать значения anotherfield.

integer — поле должно иметь корректное целочисленное значение.

ip — поле должно быть корректным IP-адресом.

ipv4 — поле должно быть IPv4-адресом.

ipv6 — поле должно быть IPv6-адресом.

json — поле должно быть валидной строкой JSON.

max:value — значение поля должно быть меньше или равно value. Размеры строк, чисел и файлов трактуются аналогично правилу size.

mimetypes:text/plain,… — MIME-тип загруженного файла должен быть одним из перечисленных:

'video' => 'mimetypes:video/avi,video/mpeg,video/quicktime'

Чтобы определить MIME-тип загруженного файла, фреймворк будет читать содержимое и пытаться угадать MIME-тип, который может отличаться от того, что указал пользователь.

mimes:foo,bar,… — MIME-тип загруженного файла должен быть одним из перечисленных.
Основное использование MIME-правила

'photo' => 'mimes:jpeg,bmp,png'

Даже если необходимо только указать расширение, это правило проверяет MIME-тип файла, читая содержимое файла и пытаясь угадать его.
Полный список MIME-типов и соответствующие им расширения можно найти в: https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types

min:value — Значение поля должно быть больше value. Размеры строк, чисел и файлов трактуются аналогично правилу size.

nullable — поле может быть равно null. Это особенно полезно при проверке примитивов, такие как строки и целые числа, которые могут содержать null значения.

not_in:foo,bar,… — поле не должно быть включено в заданный список значений. Метод Rule::notIn можно использовать для конструирования этого правила:

use IlluminateValidationRule;

Validator::make($data, [
    'toppings' => [
        'required',
        Rule::notIn(['sprinkles', 'cherries']),
    ],
]);

numeric — поле должно иметь корректное числовое или дробное значение.

present — поле для проверки должно присутствовать во входных данных, но может быть пустым.

regex:pattern — поле должно соответствовать заданному регулярному выражению.
Примечание: Для использования regex может быть необходимо определить правила в виде массива вместо использования разделителя, особенно если регулярное выражение содержит символ разделителя.

required — проверяемое поле должно иметь непустое значение. Поле считается пустым, если одно из следующих значений верно:

  • если значение равно null.
  • если значение — пустая строка.
  • если значение является пустым массивом или пустым объектом Countable.
  • если значение это загруженный файл без пути.

required_if:anotherfield,value,… — поле должно присутствовать и не быть пустым, если anotherfield равно любому value.

required_unless:anotherfield,value,… — поле должно присутствовать и не быть пустым, за исключением случая, когда anotherfield равно любому value.

required_with:foo,bar,… — проверяемое поле должно иметь непустое значение, но только если присутствует хотя бы одно из перечисленных полей (foo, bar и т.д.).

required_with_all:foo,bar,… — проверяемое поле должно иметь непустое значение, но только если присутствуют все перечисленные поля (foo, bar и т.д.).

required_without:foo,bar,… — проверяемое поле должно иметь непустое значение, но только если не присутствует хотя бы одно из перечисленных полей (foo, bar и т.д.).

required_without_all:foo,bar,… — проверяемое поле должно иметь непустое значение, но только если не присутствуют все перечисленные поля (foo, bar и т.д.).

same:field — поле должно иметь то же значение, что и поле field.

size:value — поле должно иметь совпадающий с value размер. Для строковых данных value соответствует количество символов, для массива size соответствует количеству элементов массива, для чисел — число, для файлов — размер в килобайтах.

string — поле должно быть строкой. Если вы хотите, чтобы поле было null, следует доолнитель указать это полю правило nullable.

timezone — поле должно содержать идентификатор часового пояса (таймзоны), один из перечисленных в php-функции timezone_identifiers_list.

unique:table,column,except,idColumn — значение поля должно быть уникальным в заданной таблице базы данных. Если column не указано, то будет использовано имя поля.
указание пользовательского названия столбца:

'email' => 'unique:users,email_address'

пользовательское подключение к БД
иногда может понадобиться установить собственное соединение с базой данных, как замечено выше, параметр unique:users, будет использовать соединение по умолчанию. Чтобы переопределить это, нужно указать подключение и имя таблицы через синтаксис с точкой:

'email' => 'unique:connection.users,email_address'

игнорирование ID при проверке на уникальность:
иногда потребуется игнорировать ID при проверке на уникальность. Например, рассмотрим обновление профиля пользователя, который включает в себя имя пользователя, адрес электронной почты и местоположение. Конечно, вы хотите убедиться, что адрес электронной почты является уникальным. Однако, если пользователь изменяет только имя и не изменяет электронную почту, нам не требуется вывод ошибки, но тем не менее возникнет исключение, поскольку пользователь уже является владельцем адреса электронной почты.

Для того, чтобы игнорировать ID пользователя, мы будем использовать класс Rule который позволяет гибко строить наши правила в таком случае. В примере, мы укажем правила в качестве массива вместо | символа-разделителя:

use IlluminateValidationRule;

Validator::make($data, [
    'email' => [
        'required',
        Rule::unique('users')->ignore($user->id),
    ],
]);

Если таблица использует имя столбца первичного ключа помимо id, можно указать имя столбца при вызове метода ignore:

'email' => Rule::unique('users')->ignore($user->id, 'user_id')

Добавление дополнительных условий Where:

Вы также можете указать дополнительные условия, используя метод where. Например, давайте добавим ограничение, которое проверяет, что account_id равно 1:

'email' => Rule::unique('users')->where(function ($query) {
    $query->where('account_id', 1);
})

url — поле должно быть корректным URL.

Добавление правил с условиями

Валидация при наличии поля

Иногда нужно проверить некое поле только тогда, когда оно присутствует во входных данных. Для этого добавьте правило sometimes:

$v = Validator::make($data, [
    'email' => 'sometimes|required|email',
]);

В примере выше для поля email будет запущена валидация только, когда оно присутствует в массиве $data.

Сложная составная проверка

Иногда возникает необходимость добавить правила с более сложной логикой проверки. Например, потребовать поле, только если другое поле имеет значение большее, чем 100. Или понадобится два поля, когда другое поле присутствует. Добавление этих правил не должно вызывать затруднения. Создается экземпляр Validator с постоянными правилами, которые никогда не изменятся:

$v = Validator::make($data, [
    'email' => 'required|email',
    'games' => 'required|numeric',
]);

Предположим, что веб-приложение для коллекционеров игр. Если коллекционер регистрирует в приложении игру и он владеет больше чем 100 играми в данный момент, нужно, чтобы он объяснил, почему он владеет таким количеством игр. Возможно, он управляет магазином игр, или возможно, он просто любит их собирать. Чтобы добавить это требование, можно использовать метод sometimes в экземпляре валидатора:

$v->sometimes('reason', 'required|max:500', function ($input) {
    return $input->games >= 100;
});

Первый аргумент, переданный в метод sometimes это имя поля, которое условно проверяется. Второй аргумент — правила, которые нужно добавить. Если анонимная функция передается как третий аргумент, и возвращает значение true, то правила будут добавлены. Этот метод универсален для того, чтобы строить целый комплекс условных проверок. Можно даже добавить условные проверки на нескольких полях одновременно:

$v->sometimes(['reason', 'cost'], 'required', function ($input) {
    return $input->games >= 100;
});

img

Параметр $input переданный в анонимную функцию, будет экземпляром IlluminateSupportFluent и может быть использован для доступа к полям и файлам.

Валидация массивов

Чтобы проверить, что каждая последующая электронная почта является уникальной, вы можете сделать следующее:

$validator = Validator::make($request->all(), [
    'photos.profile' => 'required|image',
]);

* — использовать одно сообщение для проверки массива полей:

$validator = Validator::make($request->all(), [
    'person.*.email' => 'email|unique:users',
    'person.*.first_name' => 'required_with:person.*.last_name',
]);

Можно использовать символ * при указании сообщений валидации в языковых файлах, значительно упрощая использование одного сообщения валидации для полей, основанных на массивах:

'custom' => [
    'person.*.email' => [
        'unique' => 'Each person must have a unique e-mail address',
    ]
],

Собственные правила валидации

Laravel предоставляет разнообразные и полезные правила для валидации. Однако, возможно, потребуется определить некоторые из своих собственных. Один из методов регистрации своих правил метод extend фасада Validator. Пример регистрации этого метода в сервис-провайдере:

<?php

namespace AppProviders;

use IlluminateSupportServiceProvider;
use IlluminateSupportFacadesValidator;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Предварительная загрузка любых сервисов приложения.
     *
     * @return void
     */
    public function boot()
    {
        Validator::extend('foo', function ($attribute, $value, $parameters, $validator) {
            return $value == 'foo';
        });
    }

    /**
     * Регистрация нового сервис-провайдера.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Анонимная функция получает четыре аргумента: имя проверяемого поля ($attribute), значение поля ($value), массив дополнительных параметров ($parameters) и экземпляр валидатора ($validator).

Класс и метод также можно передать методу extend вместо анонимной функции:

Validator::extend('foo', 'FooValidator@validate');

Определение сообщения об ошибки

Правила сообщений об ошибке можно передавть в виде массива строк в валидатор, либо добавив в файл локализации. Это сообщение должно помещаться на первом уровне массива, но не в массиве custom, который появляется только для сообщения об ошибке конкретного атрибута:

"foo" => "Your input was invalid!",

"accepted" => "The :attribute must be accepted.",

// The rest of the validation error messages...

При создании своих правил проверки, может потребоваться определить места замены для сообщений об ошибках. Можно сделать это, реализовав через метод replacer в фасаде Validator. Действие необходимо определить внутри метода boot сервис-провайдера:

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    Validator::extend(...);

    Validator::replacer('foo', function ($message, $attribute, $rule, $parameters) {
        return str_replace(...);
    });
}

Скрытые расширения

По умолчанию, когда проверяемый атрибут отсутствует или содержит пустое значение, как в правиле required, валидация не выполняется, в том числе и для расширений. Например, unique не будет выполнено для значения null:

$rules = ['name' => 'unique'];

$input = ['name' => null];

Validator::make($input, $rules)->passes(); // true

Правило должно подразумевать, что атрибут обязателен, даже, если он пуст. Для создания «скрытых» расширений используйте метод Validator::extendImplicit():

Validator::extendImplicit('foo', function ($attribute, $value, $parameters, $validator) {
    return $value == 'foo';
});

img

«Скрытое» расширение лишь подразумевает, что атрибут является обязательным.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Laravel validation custom error message
  • Laravel validate error blade
  • Laravel validate custom error
  • Laravel syntax error or access violation 1071 specified key was too long
  • Laravel route not found error

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии