By defining the validate() method you can provide your custom validation logic. For example:
php
1/** 2 * Run the validation rule.
3*/ 4publicfunctionvalidate(string$attribute,mixed$value,Closure$fail):void 5{ 6if(strtoupper($value)!==$value){ 7$fail('The :attribute must be uppercase.'); 8} 9}
Then, in a custom request you can use it as follows:
you cannot use this approach. Fortunately, an alternative one exists, but it is not currently documented.
First, define a custom generic class under app/Validators/UppercaseValidator. Note that the location is arbitrary and
you could use a different one of your choice.
$attribute: the name of the attribute being validated;
$value: the value of the attribute being validated;
$parameters: an associative array containing any rule parameter, defined after a comma (
e.g. required|my_rule,foo,baz. Here, foo and baz are parameters)
$validator the instance of the current validator.
The method should basically return a boolean value depending on whether the validation passes or fails.
However, this alone is not sufficient. You must instruct the framework about the existence of such validator. For this
purpose, in any loaded service provider, for example AppServiceProvider, you must extend the basic validator as
follows:
The name of the custom validator class (here, App\Validators\UppercaseValidator::class)
Note that your custom rule cannot contain spaces , dashses - or other special characters, but may contain
underscores _.
And that's it! You have your custom validation rule with a string alias.
Don't forget to define (after publishing your language files with php artisan lang:publish), the my_uppercase key
in your lang/<locale>/validation.php language file:
e.g.
php
1return[ 2... 3 4'my_uppercase'=>'The :attribute must be in uppercase', 5];