I'm adding custom validation rules to my Laravel 5.1 application, and I currently have it set up like this in AppServiceProvider
:
Validator::extend('word_count', 'App\CustomValidators@wordCount');
Validator::extend('required_if_not', 'App\CustomValidators@requiredIfNot');
Validator::extend('date_in_year', 'App\CustomValidators@dateInYear');
This works, but I'm wondering if there is a better method I should be using with 5.1 rather than calling the Validator facade.
For example, calling to a view no longer requires me to call View::request('template', $viewData)
or View::make('template', $viewData)
, but instead I can call view('template', $viewData)
, which cuts down on the number of namespaces I need to 'use' for my class. I can do something similar with redirects as well.
What is the best/cleanest method in Laravel 5.1 for adding custom validation rules?
Well, a probably solution here is to create a custom function (helper function as view()
) to avoid the facade.
if (! function_exists('validator_ext')) {
/**
* Adding custom rules
*
* @param string $name
* @param array $listener
* @return \Illuminate\Validation\Factory
*/
function validator_ext($name, $listener)
{
$validator = app('Illuminate\Validation\Factory');
$validator->extend($name, $listener);
return $validator;
}
}
Now you are able to call it as:
validator_ext('word_count', 'App\CustomValidators@wordCount');
Another way without using a helper function is to instantiate the validator at boot method:
$validator = app('Illuminate\Validation\Factory');
$validator->extend('word_count', 'App\CustomValidators@wordCount');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.