简体   繁体   English

Laravel - 在自定义验证中使用验证规则

[英]Laravel - Use validation rule inside Custom Validation

I am writing a custom validation rule on Laravel 4. However, I am looking forward to use the existing validation rules ( example : exists, email, min etc. ) inside it.我正在 Laravel 4 上编写自定义验证规则。但是,我期待在其中使用现有的验证规则(例如:exists、email、min 等)。 I am not sure how to do this, and I am guessing using Validator::make is not really the right way.我不知道该怎么做,我猜使用 Validator::make 并不是正确的方法。 My code is below:我的代码如下:

    Validator::extend('check_fulfilled',function($attribute,$value,$parameters){
        $movieidfield = Input::get('movieid');
                if(     empty($movieidfield )    ) return false;
                    // Here I would like to test $movieidfield 
                    //with exists and min validation rules 
    });

It would be really great if someone can help me with this.如果有人能帮我解决这个问题,那就太好了。 Thank you!谢谢!

Validation rules are composable . 验证规则是可组合的

A custom validation rule like yours shouldn't need to get values from the Input parameter bag.像您这样的自定义验证规则不需要从 Input 参数包中获取值。 Validator class already takes care of that . Validator类已经解决了这个问题

Validator::extend('check_fulfilled', function($attribute, $value, $parameters) {
    return !empty($value);
});

For example, to use your custom validation rule with other existing rules you could write when instantiating your Validator instance:例如,要将自定义验证规则与其他现有规则一起使用,您可以在实例化Validator实例时编写:

$v = Validator::make($data, array(
     'movieid' => 'check_fulfilled|email',
));

Unless you know what you are doing should you inline validation rules.除非您知道自己在做什么,否则您应该内联验证规则。

To achieve that, you could resolve Validator singleton in the app service container that is registered there by the ValidationServiceProvider .为此,您可以在ValidationServiceProvider注册的应用服务容器中解析Validator单例。

Validator::extend('check_fulfilled', function($attribute, $value, $parameters) {
    if (empty($movieidfield)) return false;
    $v = App::make('validator');

    return $v->validateExists($attribute, $value, $parameters) 
           && $v->validateEmail($attribute, $value);
});

Note that the $parameters array would need to hold values for the inlined validation rules.请注意, $parameters数组需要保存内联验证规则的值。

Refer to signature of the validation methods to understand what arguments to passed.请参阅验证方法的签名以了解要传递的参数。

Validator::validateExists($attribute, $value, $parameters)

Validator::validateEmail($attribute, $value)

Validator::validateMin($attribute, $value, $parameters)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM