Laravel How to make a custom validator?

I need to make my own validator that extends Illuminate\Validation\Validator

I read the example provided in the answer here: Custom validation in Laravel 4

But the problem is that it does not clearly show how to use a custom validator. It clearly does not invoke a custom validator. Could you give an example of how to call a custom validator.

+5
source share
2 answers

After Laravel 5.5, you can create your own custom validation rule parameter.

To create a new rule, simply run the artisan command:

 php artisan make:rule GreaterThanTen 

laravel will place the new rule class in the app/Rules directory

An example custom object validation rule might look something like this:

 namespace App\Rules; use Illuminate\Contracts\Validation\Rule; class GreaterThanTen implements Rule { // Should return true or false depending on whether the attribute value is valid or not. public function passes($attribute, $value) { return $value > 10; } // This method should return the validation error message that should be used when validation fails public function message() { return 'The :attribute must be greater than 10.'; } } 

With a specific user rule, you can use it in your controller check as follows:

 public function store(Request $request) { $request->validate([ 'age' => ['required', new GreaterThanTen], ]); } 

This method is much better than the old way to create Closures in the AppServiceProvider class.

+1
source

I do not know if this is really what you want, but in order to establish customs rules, you must first expand the user rule.

 Validator::extend('custom_rule_name',function($attribute, $value, $parameters){ //code that would validate //attribute its the field under validation //values its the value of the field //parameters its the value that it will validate againts }); 

Then add the rule to your validation rules.

 $rules = array( 'field_1' => 'custom_rule_name:parameter' ); 
0
source

Source: https://habr.com/ru/post/1245916/


All Articles