【问题标题】:Laravel 4 validators - Validate one of two fieldsLaravel 4 验证器 - 验证两个字段之一
【发布时间】:2014-08-08 03:58:35
【问题描述】:

是否有任何通用的 Laravel 验证器选项可以让我执行下面的示例?

示例:我有两个文本框,其中至少一个必须填写。一个是必须填的,两个不是必须填的。

【问题讨论】:

    标签: php laravel laravel-4


    【解决方案1】:

    看起来 Laravel 有一些内置规则:required_withoutrequired_without_all

    required_without:foo,bar,...

    required_without:foo,bar,... 仅当任何其他指定字段不存在时,才必须存在正在验证的字段。

    required_without_all:foo,bar,...

    required_without_all:foo,bar,... 只有当所有其他指定的字段都不存在时,才必须存在正在验证的字段。

    所以在你的验证中你这样做:

    $validator = Validator::make(
        [
            'textbox1' => Input::get('textbox1'),
            'textbox2' => Input::get('textbox2'),
        ],
        [
            'textbox1' => 'required_without:textbox2',
            'textbox2' => 'required_without:textbox1',
        ]
    );
    

    【讨论】:

    • 澄清一下,“必须仅在场”的意思是“必须的”。当设置其他字段时,被验证为 required_without_all 的字段也可以存在。
    【解决方案2】:

    在你的情况下,我认为一个小技巧比扩展 Validator 类更容易:

    if(empty(Input::get('textbox1')) && empty(Input::get('textbox2'))) {
        $v = Validator::make([], []); // Pass empty arrays to get Validator instance
    
        // manually add an error message
        $v->getMessageBag()->add('textbox2', 'Required if textbox1 is empty!');
    
        // Redirect back with inputs and validator instance
        return Redirect::back()->withErrors($v)->withInput();
    
    }
    

    因此,如果两个字段都为空,则重定向后,第二个文本框 (textbox2) 将显示错误消息 Required if textbox1 is empty!。但也可以使用条件验证来完成:

    $v = Validator::make([], []); // Pass empty arrays to get Validator instance
    
    // If both fields are empty then textbox2 will be required
    $v->sometimes('textbox2', 'required', function($input) {
        return empty(Input::get('textbox1')) && empty(Input::get('textbox2'));
    });
    
    $messages = array( 'required' => 'Required if textbox1 is empty!' );
    $v = Validator::make(Input::all(), $rules, $messages);
    if($v->passes) {
        // ...
    }
    

    【讨论】:

    • 值得注意的是,当字段为空时,Laravel 不会将输入传递给验证器。因此,在不覆盖 Validation 类的工作方式的情况下,似乎不可能创建一个很好的规则来应对这种情况。这可能是最好的解决方案。
    • required 是个例外,如果您没有按要求设置字段,那么 Laravel 会假定 null 或空值是可以的。这使得很难制定像require_one:field2,field3 这样的规则。如果您检查 Validation 类中的 validate 方法,它会被注释为 Unless the rule implies that the attribute is required, rules are not run for missing values.
    • 你到底在说什么,自己看这段代码。两者都有效。查看一个示例hereLaravel 不会传递空字段,这就是它适用于 required 的原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-08
    • 2018-09-08
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 2021-08-01
    • 2016-03-18
    相关资源
    最近更新 更多