Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
589 views
in Technique[技术] by (71.8m points)

php - Custom validator in Laravel 5

I am upgrading my Laravel application from 4 to 5. However, I have a custom validator that I cannot get to work.

In L4, I made a validators.php file and included it in global.php using require app_path().'/validators.php';.

I tried doing somewhat the same in L5. I dropped a validator in app/Validators/Validators.php, and updated my composer.json.

"files": [
    "app/Validators/Validators.php"
]

However, now nothing renders on any page. What've I done wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try the following:

  1. Make a bind class where you can implement each rule you want extending Validator class.
  2. Make a service provider that extends ServiceProvider.
  3. Add your custom validator provider at config/app.php file.

You can create the bind at Services folder like this:

namespace MyAppServices;

class Validator extends IlluminateValidationValidator{

    public function validateFoo($attribute, $value, $parameters){  
        return $value == "foo"
    }
}

Then, use a service provider to extends the core:

namespace MyAppProviders;

use MyAppServicesValidator;
use IlluminateSupportServiceProvider;

class ValidatorServiceProvider extends ServiceProvider{

    public function boot()
    {
        Validator::resolver(function($translator, $data, $rules, $messages)
        {
            return new Validator($translator, $data, $rules, $messages);
        });
    }

    public function register()
    {
    }
}

Finally, import your service provider at config/app.php like so:

'providers' => [
    ...
    ...
    'MyAppProvidersValidatorServiceProvider';
]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...