Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel How to Make Custom Validator?

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

I have read an example given in an answer here: Custom validation in Laravel 4

But the problem is it doesn't clearly show how to use the custom validator. It doesn't call the custom validator explicitly. Could you give me an example how to call the custom validator.

like image 690
CherryBelle Avatar asked Mar 28 '16 15:03

CherryBelle


People also ask

What is custom validation in laravel?

Customizing Validation Rules Using Laravel. Share. While you are working with user input and forms, validating the common fields and extracting the exact validation rules makes the code easier to maintain and read. You can make the code powerful by using the Laravel custom validation rule with parameters.

What does custom validator mean?

The CustomValidator control is a separate control from the input control it validates, which allows you to control where the validation message is displayed. Validation controls always perform validation on the server.


2 Answers

After Laravel 5.5 you can create you own Custom Validation Rule object.

In order to create the new rule, just run the artisan command:

php artisan make:rule GreaterThanTen

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

An example of a custom object validation rule might look something like:

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 the custom rule defined, you might use it in your controller validation like so:

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

This way is much better than the old way of create Closures on the AppServiceProvider Class

like image 196
Hemerson Varela Avatar answered Oct 03 '22 14:10

Hemerson Varela


I don't know if this is what you want but to set customs rules you must first you need to extend the custom 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'
);
like image 42
Carlos Salazar Avatar answered Oct 03 '22 15:10

Carlos Salazar