Laravel 5 中的自定义验证器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28417977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:53:07  来源:igfitidea点击:

Custom validator in Laravel 5

phpvalidationlaravellaravel-5

提问by Maeh

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

我正在将我的 Laravel 应用程序从 4 升级到 5。但是,我有一个无法开始工作的自定义验证器。

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

在L4,我做了一个validators.php文件并已将其列入global.php使用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.

我尝试在 L5 中做一些相同的事情。我在app/Validators/Validators.php 中删除了一个验证,并更新了我的composer.json

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

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

但是,现在任何页面上都没有呈现任何内容。我做错了什么?

回答by manix

Try the following:

请尝试以下操作:

  1. Make a bind class where you can implement each rule you want extending Validatorclass.
  2. Make a service provider that extends ServiceProvider.
  3. Add your custom validator provider at config/app.phpfile.
  1. 制作一个绑定类,您可以在其中实现您想要扩展Validator类的每个规则。
  2. 制作一个扩展的服务提供者ServiceProvider
  3. config/app.php文件中添加您的自定义验证器提供程序。

You can create the bind at Servicesfolder like this:

您可以Services像这样在文件夹中创建绑定:

namespace MyApp\Services;

class Validator extends \Illuminate\Validation\Validator{

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

Then, use a service provider to extends the core:

然后,使用服务提供者扩展核心:

namespace MyApp\Providers;

use MyApp\Services\Validator;
use Illuminate\Support\ServiceProvider;

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.phplike so:

最后,config/app.php像这样导入你的服务提供者:

'providers' => [
    ...
    ...
    'MyApp\Providers\ValidatorServiceProvider';
]

回答by Rabb-bit

so here's what I did on adding a custom validation. this is for laravel 5.1

所以这就是我在添加自定义验证时所做的。这是针对laravel 5.1

  1. run PHP Artisan make:request MyFormValidationRequestfile is created under app\Requests\MyFormValidationRequest.php
  1. 运行PHP Artisan make:request MyFormValidationRequest文件是在下面创建的app\Requests\MyFormValidationRequest.php

Here's the initial code:

这是初始代码:

<?php

namespace App\Http\Requests;
use App\Http\Requests\Request;

class MyFormValidationRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {

        return [
            //

        ];
    }
}


IMPORTANT: Change the return value of authorize()method to true, if you're not doing any authentication. it's initial value is false. else you get a white page with a "Forbidden" error message.

重要提示authorize()如果您不进行任何身份验证,请将方法的返回值更改为 true。它的初始值为false。否则,您会看到一个带有“禁止”错误消息的白页。



  1. I added a rule under the function rules(), here's what it looks like

    public function rules() {
        return [
            'activeuntil' => 'today_onwards'
        ];
    }
    
  1. 我在函数下添加了一个规则rules(),这是它的样子

    public function rules() {
        return [
            'activeuntil' => 'today_onwards'
        ];
    }
    

today_onwardsis my new validation.

today_onwards是我的新验证。

  1. I created a folder named 'Services' under App folder

  2. I created a file named 'ValidatorExtended.php' under App\Services folder , here's the code below:

     <?php 
    
         namespace App\Services;     
         use Illuminate\Validation\Validator;
         use Carbon\Carbon;
    
         class ValidatorExtended extends Validator {
    
             private $_custom_messages = array(        
                 "today_onwards" => "The :attribute must be today onwards",
             );
    
             public function __construct( $translator, $data, $rules, $messages = array(), $customAttributes = array() ) {
                 parent::__construct( $translator, $data, $rules, $messages, $customAttributes );
    
                 $this->_set_custom_stuff();
             }
    
             protected function _set_custom_stuff() {
                 //setup our custom error messages
                 $this->setCustomMessages( $this->_custom_messages );
             }
    
             protected function validateTodayOnwards( $attribute, $value ) {     
                 $now =  strtotime('-1 day');
                 $valueDateFormat =  strtotime($value);
    
                 if($valueDateFormat > $now){
                     return true;
                 }
                 else {
                     return false;
                 }        
            }
        }
    
  1. 我在 App 文件夹下创建了一个名为“Services”的文件夹

  2. 我在 App\Services 文件夹下创建了一个名为“ValidatorExtended.php”的文件,代码如下:

     <?php 
    
         namespace App\Services;     
         use Illuminate\Validation\Validator;
         use Carbon\Carbon;
    
         class ValidatorExtended extends Validator {
    
             private $_custom_messages = array(        
                 "today_onwards" => "The :attribute must be today onwards",
             );
    
             public function __construct( $translator, $data, $rules, $messages = array(), $customAttributes = array() ) {
                 parent::__construct( $translator, $data, $rules, $messages, $customAttributes );
    
                 $this->_set_custom_stuff();
             }
    
             protected function _set_custom_stuff() {
                 //setup our custom error messages
                 $this->setCustomMessages( $this->_custom_messages );
             }
    
             protected function validateTodayOnwards( $attribute, $value ) {     
                 $now =  strtotime('-1 day');
                 $valueDateFormat =  strtotime($value);
    
                 if($valueDateFormat > $now){
                     return true;
                 }
                 else {
                     return false;
                 }        
            }
        }
    

Note:the validateTodayOnwards method is where you put your logic. the name of the method should always start in "validate" then the name of your new validation key which should be in title case,

注意:validateTodayOnwards 方法是您放置逻辑的地方。方法的名称应始终以“validate”开头,然后是新验证密钥的名称,该名称应在标题大小写中,

Another noteyour validation key should be separated by underscore and all small letters, in this case, "today_onwards". the underscore should be put before all first capital letters in the method name. I hope I explained it good.

另请注意,您的验证密钥应由下划线和所有小写字母分隔,在本例中为“today_onwards”。下划线应该放在方法名称中的所有第一个大写字母之前。我希望我解释得很好。

TodayOnwards method is equivalent to validation name of "today_onwards",

TodayOnwards 方法相当于“today_onwards”的验证名称,

another example, if I created validateOldPassword, your validation key should be "old_password".

另一个例子,如果我创建了validateOldPassword,你的验证密钥应该是“old_password”。

  1. I added below code in app\Providers\AppServiceProvider.phpinside boot()method.

    Validator::resolver(function($translator, $data, $rules, $messages = array(), $customAttributes = array())
    {
        return new ValidatorExtended($translator, $data, $rules, $messages, $customAttributes);
    });
    
  2. Don't forget to add below library, one is the Validator class and the other is your own class which is the "ValidatorExtended".

    use App\Services\ValidatorExtended;
    
    use Illuminate\Support\Facades\Validator;
    
  3. Here's what the whole file looks like, [app\Providers\AppServiceProvider.php]

    <?php
    
        namespace App\Providers;
    
        use Illuminate\Support\ServiceProvider;
        use App\Services\ValidatorExtended;
        use Illuminate\Support\Facades\Validator;
    
        class AppServiceProvider extends ServiceProvider
        {
        /**
         * Bootstrap any application services.
         *
         * @return void
        */
             public function boot()
             {
                 //
                 Validator::resolver(function($translator, $data, $rules, $messages = array(), $customAttributes = array())
                 {
                     return new ValidatorExtended($translator, $data, $rules, $messages, $customAttributes);
                 });
             }
    
             /**
              * Register any application services.
              *
              * @return void
             */
             public function register()
             {
                //
            }
        } 
    
  4. That's it. done. you created your own custom validation.

  5. Additionally, if you want to use it in your controller, below is the code:

    class testController extends Controller
    {
        public function updatePass(MiscValidation $request){
            //code here
        }
    }
    
  1. 我在app\Providers\AppServiceProvider.php内部boot()方法中添加了以下代码。

    Validator::resolver(function($translator, $data, $rules, $messages = array(), $customAttributes = array())
    {
        return new ValidatorExtended($translator, $data, $rules, $messages, $customAttributes);
    });
    
  2. 不要忘记添加下面的库,一个是 Validator 类,另一个是您自己的类,即“ ValidatorExtended”。

    use App\Services\ValidatorExtended;
    
    use Illuminate\Support\Facades\Validator;
    
  3. 这是整个文件的样子,[ app\Providers\AppServiceProvider.php]

    <?php
    
        namespace App\Providers;
    
        use Illuminate\Support\ServiceProvider;
        use App\Services\ValidatorExtended;
        use Illuminate\Support\Facades\Validator;
    
        class AppServiceProvider extends ServiceProvider
        {
        /**
         * Bootstrap any application services.
         *
         * @return void
        */
             public function boot()
             {
                 //
                 Validator::resolver(function($translator, $data, $rules, $messages = array(), $customAttributes = array())
                 {
                     return new ValidatorExtended($translator, $data, $rules, $messages, $customAttributes);
                 });
             }
    
             /**
              * Register any application services.
              *
              * @return void
             */
             public function register()
             {
                //
            }
        } 
    
  4. 就是这样。完毕。您创建了自己的自定义验证。

  5. 此外,如果你想在你的控制器中使用它,下面是代码:

    class testController extends Controller
    {
        public function updatePass(MiscValidation $request){
            //code here
        }
    }
    

Instead of using Request Class you use your own class which is an extension of the Request class.

您可以使用自己的类,而不是使用 Request Class,它是 Request 类的扩展。