0

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?

Lisa
  • 2,102
  • 7
  • 26
  • 44
  • 1
    Lisa, somethings the shortest way is not the best/cleanest. When the project is getting large is good to keep things in order instead putting extra effort-time just to save some characters. Take a look to this way: http://stackoverflow.com/questions/28417977/custom-validator-in-laravel-5/28425173#28425173 – manix Oct 14 '15 at 20:49
  • This question is part of a refactoring session that I'm doing on my project. It's less to minimize the number of characters that are used and more to learn best practices for Laravel 5.1. This application was upgraded from Laravel 4.1, so there's a lot in there that's still following those practices. – Lisa Oct 14 '15 at 20:53

1 Answers1

1

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');
manix
  • 14,537
  • 11
  • 70
  • 107
  • 1
    Thanks, both of those solutions look interesting. I'll play around with them and see how they go! – Lisa Oct 15 '15 at 19:35