Request form validation and error handling


 laravel-request-validation

brief introduction

Laravel provides several methods to validate the request input data. By default, Laravel's controller base class uses ValidatesRequests trait, This trait provides a convenient method to validate the input HTTP request through various powerful validation rules.

quick get start

To master the powerful validation features of Laravel, let's first take a look at a complete validation form and return an error message to the user.

Define route

First, let's assume that routes/web.php The file contains the following routes:

 //Show Create Blog Post Form Route::get('post/create', ' PostController@create '); //Store new blog posts Route::post('post', ' PostController@store ');

obviously, GET The route displays a form for the user to create a new blog post, and the POST route stores the new blog post to the database.

Create Controller

Next, let's look at an example of a simple controller that handles these routes. First, we will store Method left blank:

 <? php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class PostController extends Controller { /** *Displays the form for creating a new blog post * * @return Response */ public function create() { return view('post.create'); } /** *Store new blog posts * * @param  Request  $request * @return Response */ public function store(Request $request) { //Verify and store blog posts } }

Write verification logic

Now we are ready to fill in with the logic to verify the input of the new blog post store method. We use Illuminate\Http\Request Object validate Method. If the validation rule passes, the code will continue to execute; On the contrary, if the verification fails, an exception will be thrown and the corresponding error response will be automatically sent to the user. In this traditional HTTP request case, a redirect response will be generated. If it is an AJAX request, a JSON response will be returned.

To better understand validate Methods, let's review store method:

 /** *Store blog posts * * @param  Request  $request * @return Response */ public function store(Request $request){ $validatedData = $request->validate([ 'title' => 'required|unique:posts|max:255', 'body' => 'required', ]); //Validated, stored in database }

As you can see, we just pass in the expected validation rules to validate method. Again, if the validation fails, the corresponding response will be generated automatically. If the verification is passed, the controller will continue to execute.

Note: Before actually executing the code, you need to create it in the database posts Data table, because it is used here unique:posts This validation rule will go to the database to query whether the incoming title already exists to ensure uniqueness.

Abort subsequent rule validation after the first validation failure

Sometimes you may want to stop checking other validation rules of this attribute after the first validation failure. To implement this function, you can assign bail As the first rule:

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

In this example, if title On attribute required If the rule validation fails, it will not be checked unique Rules will be verified in the order of allocation.

Considerations for nested attributes

If the HTTP request contains "nested" parameters, you can use "." to specify them in the validation rules:

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

Such validation rules are applicable to the validation of the following label requests:

 <form method="POST" action="{{route('posts.store')}}"> {{csrf_field()}} <input type="text" name="title"/> <input type="text" name="author[name]"/> <input type="text" name="author[desc]"/> <textarea cols="20" rows="5" name="body"></textarea> <button type="submit">submit</button> </form>

Display validation error message

What if the request input parameters fail to pass the given validation rules? As mentioned earlier, Larravel will automatically redirect the user back to the previous location. In addition, all validation error messages are automatically stored in the One time session , we can see the data structure of the session data:

Notice that we are not in GET Explicitly bind the error information to the view in the route. This is because Laravel always checks the error information from the session data, and automatically binds it to the view if any. Therefore, it is worth noting that there is always a $errors Variable, which allows you to use it conveniently and safely in the view. $errors Variable is a Illuminate\Support\MessageBag example. To learn more about this object, see its Corresponding document

Note: $errors The variable will pass web In the middleware group Illuminate\View\Middleware\ShareErrorsFromSession Middleware is bound to the view. If the middleware is used $errors Variables are always valid in the view, which is convenient for you to use at any time.

Therefore, in our example, if the authentication fails, the user will be redirected to the controller create Method to allow us to display 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 -->

If the verification fails, an error message will be displayed when you jump back to the form page:

Precautions for optional fields

By default, Larravel comes with TrimStrings and ConvertEmptyStringsToNull Middleware, which are located in App\Http\Kernel Class in the global middleware stack. For this reason, you often need to mark the "optional" request field as nullable ——If you don't want the validator to null If it is judged as invalid. For example:

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

In this example, we specify publish_at Fields can be null Or a valid date format. If nullable Not added to the validation rule, the validator will null The date is determined to be invalid.

AJAX Request&Verification

In the above example, we used traditional forms to send data to applications. However, in real scenarios, many applications use AJAX requests. Use in AJAX requests validate Method, Larravel does not generate a redirect response. Instead, Larravel generates a JSON response containing validation error information. The JSON response will carry an HTTP status code four hundred and twenty-two

Complex form request validation

Create Form Request

For more complex verification scenarios, you may want to create a "form request". A form request is a custom request class that contains validation logic. To create a form validation class, you can use the Artisan command make:request

 php artisan make:request StoreBlogPost

The generated class is located in app/Http/Requests If the directory does not exist, run make:request The command will be generated for us. Next, we add a few validation rules to the rules method:

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

So, how does the validation rule take effect? All you have to do is type prompt the request class in the controller method. In this way, the form input request will be verified before the controller method is called, which means you don't need to mix the controller method and verification logic:

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

If the verification fails, the redirect response will be generated and the user will be returned to the previous location. The error message will also be stored in a one-time session for display in the view. If it is an AJAX request four hundred and twenty-two The HTTP response of the status code will be returned to the user. The response data also contains the validation error information in JSON format.

Add verified hook to form request

If you want to add a "post verification" hook to the form request, you can use withValidator method. This method receives a complete construction validator, thus allowing you to call any validator method before the validation rule is executed:

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

Authorization Form Request

The form request class also contains a authorize Method, you can check whether the authenticated user has permission to update the specified resource. For example, if a user tries to update a blog comment, he must be the owner of the comment. for instance:

 /** *Determine whether the user has the right to request * * @return bool * @translator laravelacademy.org */ public function authorize() { $comment = Comment::find($this->route('comment')); return $comment && $this->user()->can('update', $comment); }

Since all requests inherit from the Larravel request base class, we can use user Method to obtain the current authenticated user. Note that in the above example route Method. This method gives the user access to the called route URI parameters, such as {comment} Parameters:

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

If authorize Method return false , one containing four hundred and three The HTTP response of the status code will automatically return and the controller method will not be executed.

If you plan to invoke authorization logic in other parts of the application authorize Simple return in method true That is:

 /** *Judge whether the requesting user is authorized * * @return bool */ public function authorize(){ return true; }

Custom error messages

You can rewrite messages Method defines the error message used by the form request. This method should return the attribute/rule pair array and its corresponding error message:

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

Manually create a validator

If you don't want to use the validate Method, you can use Validator The facade manually creates an instance of the verifier make Method can be used to generate a new validator instance:

 <? php namespace App\Http\Controllers; use Validator; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class PostController extends Controller{ /** *Store new blog posts * * @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 blog posts } }

Pass to make The first parameter of the method is the data to be validated, and the second parameter is the validation rule to be applied to the data.

After the check request fails to pass the verification, you can use the withErrors Method to store error data in a one-time session. When using this method, $errors Variable retargeting is automatically shared between views backward, allowing you to easily display it to users, withErrors Method receives a validator, or a MessageBag , or a PHP array.

redirect automatically

If you want to create a verifier instance manually, but still use the validate Method, you can call the validate If the authentication fails, the user will be redirected automatically, or if it is an AJAX request, the JSON response will be returned:

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

Naming Error Packages

If you have multiple forms on a single page, you may need to name them incorrectly MessageBag , which allows you to get error information for the specified form. Just pass the name as the second parameter to withErrors That is:

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

Then you can go from $errors Access named MessageBag example:

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

After verifying the hook

The verifier allows you to add callbacks after the verification is completed. This mechanism allows you to easily perform more verification, and even add more error information to the message collection. Use the after Method:

 $validator = Validator::make(...); $validator->after(function($validator) { if ($this->somethingElseIsInvalid()) { $validator->errors()->add('field', 'Something is wrong with this field!'); } }); if ($validator->fails()) { // }

Handling error messages

call Validator On instance errors Method, a Illuminate\Support\MessageBag Instance, which contains a variety of convenient methods for processing error information. Valid by default in all views $errors Variable is also a MessageBag example.

Get the first error message of a field

To get the first error message of the specified field, you can use the first method:

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

Get all error information of the specified field

If you want to simply get all the error information arrays of the specified field, use get method:

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

If it is an array form field, you can use * Get all array element error information:

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

Get all error messages for all fields

To get all error messages for all fields, use the all method:

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

Determine whether there is an error message for a field in the message

has The method can be used to determine whether the error message contains a given field:

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

Custom error messages

If necessary, you can use custom error messages instead of the default ones. There are many ways to specify custom messages. First, you can pass custom information as the third parameter to Validator::make method:

 $messages = [ 'required' => 'The :attribute field is required.', ]; $validator = Validator::make($input, $rules, $messages);

In this example, :attribute The placeholder will be replaced by the actual field name during validation. You can also use other placeholders in the validation message, such as:

 $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', ];

Specify custom information for the given attribute

Sometimes you may only want to specify custom error messages for specific fields, which can be achieved through ".". First specify the attribute name, then the rules:

 $messages = [ 'email. required'=>'Email address cannot be empty!', ];

Specify custom messages in the language file

In many cases, you may want to specify custom messages in the language file instead of passing them directly to Validator To implement this, add a message to resources/lang/xx/validation.php Of language files custom Array:

 'custom' => [ 'email' => [ 'required '=>' Email address cannot be empty! ', ], ],

Specify custom attributes in the language file

If you want to verify the message's :attribute Replace some with custom attribute names, which can be found in the language file resources/lang/xx/validation.php Of attributes Specify custom name in the array:

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

Complete set of validation rules

The following is a list of valid rules and their functions:

  • Accepted
  • Active URL
  • After (Date)
  • After Or Equal(Date)
  • Alpha
  • Alpha Dash
  • Alpha Numeric
  • Array
  • Before (Date)
  • Before Or Equal(Date)
  • Between
  • Boolean
  • Confirmed
  • Date
  • Date Equals
  • Date Format
  • Different
  • Digits
  • Digits Between
  • Dimensions (picture files)
  • Distinct
  • E-Mail
  • Exists (Database)
  • File
  • Filled
  • Image (File)
  • In
  • In Array
  • Integer
  • IP Address
  • JSON
  • Max
  • MIME Types (File)
  • MIME Type By File Extension
  • Min
  • Nullable
  • Not In
  • Numeric
  • Present
  • Regular Expression
  • Required
  • Required If
  • Required Unless
  • Required With
  • Required With All
  • Required Without
  • Required Without All
  • Same
  • Size
  • String
  • Timezone
  • Unique (Database)
  • URL

accepted

The value of the validation field must be yes on one or true , which is useful when "Agree to Service Agreement".

active_url

The validation field must be based on PHP functions dns_get_record With A or AAAA record values.

after:date

The validation field must be a value after the given date. The date will pass the PHP function strtotime Delivery:

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

Instead of passing a date string to strtotime Execution:

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

after_or_equal:date

The validation field must be a value greater than or equal to the given date. For more information, refer to after:date Rules.

alpha

The validation field must be a letter.

alpha_dash

The validation field can contain letters and numbers, as well as dashes and underscores.

alpha_num

The validation field must be a letter or number.

array

The validation field must be a PHP array.

before:date

and after:date In contrast, the validation field must be a numeric value before the specified date, and the date will be passed to PHP strtotime Function.

before_or_equal:date

The validation field must be less than or equal to the given date. The date will be passed to PHP's strtotime Function.

between:min,max

Verify that the field size is between the given minimum and maximum values, and that strings, numbers, arrays, and files can all be used as size The same rule applies to this rule:

 'name' => 'required|between:1,20'

boolean

The validation field must be able to be converted to a Boolean value, receiving true , false , one , zero , "1" and "0" And so on.

confirmed

Validation field must have a matching field foo_confirmation , for example, if the validation field is password , you must enter a matching password_confirmation Field.

date

The validation field must be a PHP based strtotime Valid date of function

date_equals:date

The validation field must be equal to the given date, which will be passed to PHP strtotime Function.

date_format:format

The validation field must match the specified format. You can use the PHP function date or date_format to validate the field.

different:field

The validation field must be a value different from the specified field.

digits:value

The validation field must be a number with a length of the value specified by value.

digits_between:min,max

The validation field value length must be between the minimum and maximum values.

dimensions

The verified image size must meet the constraints specified by the specified parameters:

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

Valid constraints include: min_width , max_width , min_height , max_height , width , height , ratio

Ratio Constrains the ratio of width to height, which can be expressed by 3/2 Or floating point number one point five To represent:

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

Since this rule requires multiple parameters, you can use Rule::dimensions Method to construct the rule:

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

distinct

When processing an array, the validation field cannot contain duplicate values:

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

email

The validation field must be a properly formatted email address

exists:table,column

The validation field must exist in the specified data table

Basic use:

 'state' => 'exists:states'

Specify custom column names:

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

Sometimes, you may need to exists The query specifies the database connection to be used, which can be realized by. pre database connection before the table name:

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

If you want to customize the query executed by the validation rule, you can use Rule Class to define rules. In this example, we also specify the validation rules in the form of an array instead of using | Characters to qualify them:

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

file

The verification field must be a file successfully uploaded.

filled

The validation field cannot be empty if it exists.

image

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

in:foo,bar…

The value of the validation field must be in the given list, because this rule often requires us to implode , we can use Rule::in To construct this rule:

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

In_array: another field

The validation field must be in the Another field Value exists in.

integer

The validation field must be an integer.

ip

The validation field must be an IP address.

ipv4

The validation field must be an IPv4 address.

ipv6

The validation field must be an IPv6 address.

json

The validation field must be a valid JSON string

max:value

The validation field must be less than or equal to the maximum value, and size The rules are used in the same way.

mimetypes:text/plain…

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

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

To determine the MIME type of the uploaded file, the framework will read the file content to guess the MIME type, which may be different from the client MIME type.

mimes:foo,bar,…

The MIME type of the validation file must be one of the extension types listed in the rule

Basic use of MIME rules:

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

Although you only specify the extension, this rule actually verifies the MIME type of the file obtained by reading the file content.

A complete list of MIME types and their corresponding extensions can be found here: http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types

min:value

And max:value In contrast, the validation field must be greater than or equal to the minimum value. For string, numeric value, array, file field, and size The rules are used in the same way.

nullable

The validation field can be null , which verifies that some null This is useful for raw data such as integers or strings.

not_in:foo,bar,…

The validation field value cannot be in the given list, and in The rules are similar. We can use Rule::notIn Methods to build rules:

 use Illuminate\Validation\Rule; Validator::make($data, [ 'toppings' => [ 'required', Rule::notIn(['sprinkles', 'cherries']), ], ]);

numeric

Validation field must be numeric

present

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

regex:pattern

The validation field must match the given regular expression.

Note: Use regex When the mode is set, the rule must be placed in the array, and the pipe separator cannot be used, especially when the pipe symbol has been used in the regular expression.

required

The value of the validation field cannot be empty. The field values are empty in the following cases:

  • Value is null
  • Value is an empty string
  • The value is an empty array or empty Coutable object
  • The value is upload file but the path is empty

required_if:anotherfield,value,…

Validate field in anotherfield Equal to the specified value value Must exist and cannot be empty

required_unless:anotherfield,value,…

Unless anotherfield Field equals value , otherwise the validation field cannot be empty

required_with:foo,bar,…

The validation field is only necessary if any other specified field exists

required_with_all:foo,bar,…

Validation fields are required only when all specified fields exist

required_without:foo,bar,…

The validation field is required only when any specified field does not exist

required_without_all:foo,bar,…

Validation fields are required only when all specified fields do not exist

same:field

The given field and the validation field must match

size:value

The validation field must have and the given value value Matching size/size, for strings, value Is the corresponding number of characters; For numerical values, value Is the given integer value; For arrays, value Is the array length; For documents, value Is the number of kilobytes of the corresponding file (KB)

string

The validation field must be a string. If the field is allowed to be empty, it needs to be assigned nullable Rules to this field.

timezone

Verification characters must be based on PHP functions timezone_identifiers_list Valid time zone ID of

unique:table,column,except,idColumn

The validation field must be unique on the given data table. If you do not specify column Option, the field name will be the default column

Specify custom column names:

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

Custom database connection

Sometimes, you may need to customize the database connection generated by the verifier. As seen above, set unique:users As a validation rule, the default database connection will be used to query the database. To override the default connection, use "." after the data table name to specify the connection:

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

Enforce a unique rule that ignores a given ID:

Sometimes, you may want to ignore the given ID in the unique check, for example, consider a user name In the "Update Attribute" interface of the email address and location, you will verify that the email address is unique. However, if the user only changes the user name field and does not change the email field, you do not want to throw verification errors because the user already has the email address. You only want to throw verification errors when the email provided by the user has been used by others.

To tell the authenticator to ignore the user ID, you can use the Rule Class to define this rule. We should also specify the validation rule in an array instead of using the | To define the rules:

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

If your data table uses a primary key field that is not id , you can call ignore Specify the field name when using the method:

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

Add additional where clauses:

use where You can also specify additional query constraints when you customize the query. For example, let's add a validation account_id by one Constraints for:

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

url

The validation field must be a valid URL.

Add Condition Rule

Validate when present

In some scenarios, you may want to perform verification checks when only one field exists. To quickly implement this, add sometimes Rule to rule list:

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

In the example above, email Field only exists in $data Array will be validated.

Note: If you try to verify a field that always exists but may be empty, refer to Precautions for optional fields

Verification of complex conditions

Sometimes you may want to add validation rules based on more complex conditional logic. For example, you may want to require a given field to be mandatory only when the value of another field is greater than 100, or you may want to require that both fields have a given value only when the other field exists. Adding this validation rule is not a headache. First, create a static rule that will never change Validator example:

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

Let's assume that our Web application serves game collectors. If a game collector has registered our application and owns more than 100 games, we want them to explain why they have so many games. For example, maybe they are running a second-hand game store, or they just like collecting games. To add this condition, we can use Validator On instance sometimes method:

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

Pass to sometimes The first parameter of the method is the name field we need to verify conditionally, and the second parameter is the rule we want to add. If it is returned as the closure of the third parameter true , the rule is added. This method makes it easy to build complex conditional validation. You can even add conditional validation for multiple fields at one time:

 $v->sometimes(['reason', 'cost'], 'required', function($input) { return $input->games >= 100; });
Note: passed to closure $input The parameter is Illuminate\Support\Fluent An instance of that can be used to access inputs and files.

Verify array input

Verifying the form array input field is no longer a pain. For example, if the incoming HTTP request contains photos[profile] Fields can be verified as follows:

 $validator = Validator::make($request->all(), [ 'photos.profile' => 'required|image', ]);

We can also verify every element of the array, for example, to verify every email Whether it is unique or not, you can do so (the array fields submitted are two-dimensional arrays, such as person[][email] or person[test][email] ):

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

Similarly, you can use the * The character specifies the validation message, so that a single validation message can be used to define validation rules based on array fields:

 'custom' => [ 'person.*.email' => [ 'unique'=>'Everyone's email address must be unique', ] ],

Custom validation rules

Using Rule Objects

As mentioned above, Laravel provides a variety of useful validation rules; However, you may still need to specify some of your own validation rules. One way to register custom validation rules is to use rule objects. To generate a new rule object, you can use Artisan commands make:rule Next, we use this command to generate a rule to verify whether the string is capitalized. The new rule object class generated is located in app/Rules catalog:

 php artisan make:rule Uppercase

After a rule is created, you can define behavior methods. A rule object contains two methods: passes and message passes Method receives the property value and name, and returns based on whether the property value is valid true or false message Method is used to return a validation error message when validation fails:

 <? php namespace App\Rules; use Illuminate\Contracts\Validation\Rule; class Uppercase implements Rule { /** * Determine if the validation rule passes. * * @param  string  $attribute * @param  mixed  $value * @return bool */ public function passes($attribute, $value) { return strtoupper($value) === $value; } /** * Get the validation error message. * * @return string */ public function message() { return 'The :attribute must be uppercase.'; } }

Of course, you can message Call auxiliary function in method trans To return an error message defined in the language file:

 /** * Get the validation error message. * * @return string */ public function message() { return trans('validation.uppercase'); }

After the rules are defined, they can be provided to the verifier together with other validation rules in the form of rule object instances:

 use App\Rules\Uppercase; $request->validate([ 'name' => ['required', new Uppercase], ]);

Using Extensions

Another way to register custom validation rules is to use the Validator On the facade extend method. We are in a service provider( AppServiceProvider )Use this method to register a custom validation rule in:

 <? php namespace App\Providers; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\Validator; class AppServiceProvider extends ServiceProvider { /** *Start application service * * @return void */ public function boot() { Validator::extend('foo', function($attribute, $value, $parameters, $validator) { return $value == 'foo'; }); } /** *Registered Service Provider * * @return void */ public function register() { // } }

The custom validator closure receives four parameters: the property name to be validated, the property value, the parameter array passed to the rule, and Validator example.

You can also pass classes and methods to extend Method instead of closure:

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

Define error messages

You also need to define error messages for custom rules. You can use inline custom message arrays or add entries to the validation language file to achieve this. Messages should be placed in the first dimension of the array, not in the custom In array:

 "foo" => "Your input was invalid!", "accepted" => "The :attribute must be accepted.", //Verify other parts of the error message

When creating a custom validation rule, you may sometimes need to define a custom placeholder for error messages. You can create a custom validator and call Validator On the facade replacer Method. In the service provider's boot Write the following code in the method:

 /** *Start application service * * @return void * @translator laravelacademy.org */ public function boot(){ Validator::extend(...); Validator::replacer('foo', function($message, $attribute, $rule, $parameters) { return str_replace(...); }); }

Implicit expansion

By default, if the verified attribute is not provided or the verification rule is required If the value is empty, normal validation rules, including custom extensions, will not be executed. For example, unique Rules will not be verified null Value:

 $rules = ['name' => 'unique']; $input = ['name' => null]; Validator::make($input, $rules)->passes(); //  true

If you need to validate the attribute even if it is empty, you must imply that the attribute is necessary. To create an implicit extension, you can use Validator::extendImplicit() method:

 Validator::extendImplicit('foo', function($attribute, $value, $parameters, $validator) { return $value == 'foo'; });
Note: An implicit extension only implies that the attribute is necessary. It depends on you whether it is missing or null.

give the thumbs-up Cancel Like Collection Cancel Collection

<<Previous: Session Implementation, Configuration and Use Details

>>Next: Exception handling&error log