Laravel 4验证器 - 验证两个字段之一

时间:2014-06-18 01:16:52

标签: php laravel laravel-4

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

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

2 个答案:

答案 0 :(得分:5)

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

<强> required_without:foo,bar,...

  

required_without:FOO,酒吧,...   只有在不存在任何其他指定字段时,才能使用验证字段。

<强> required_without_all:foo,bar,...

  

required_without_all:FOO,酒吧,...   只有当所有其他指定字段都不存在时,验证字段才必须存在。

因此,在您的验证中,您可以:

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

答案 1 :(得分:1)

在你的情况下,我认为有点破解比扩展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) {
    // ...
}