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.
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.
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.
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
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'
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With