繁体   English   中英

Laravel-两个输入值都不能没有如何验证?

[英]Laravel - both input values can't be no how to validate?

我正在将Laravel用于一个项目,并且想知道如何验证我面临的特定场景。 如果可能的话,我想使用Laravel的本机功能来做到这一点?

我有一个包含两个问题(作为下拉菜单)的表格,对于这两个问题,答案都可以是或否,但是,如果两个下拉菜单均等于“否”,则它应该引发验证错误,但它们都可以是。

我已经查看了laravel文档,但是不确定如果可以使用一个规则,那么在这里适用什么规则? 在这种情况下,我需要编写自己的规则吗?

很简单:

假设两个字段名称分别为foobar

然后:

 // Validate for those fields like $rules = ['foo'=>'required', 'bar'=>'required'] etc

 // if validation passes, add this (i.e. inside if($validator->passes()))

 if($_POST['foo'] == 'no' && $_POST['bar'] == 'no')
 {
     $messages = new Illuminate\Support\MessageBag;
     $messages->add('customError', 'both fields can not be no');
     return Redirect::route('route.name')->withErrors($validator);
 }

检索时会出现错误信息。

如果您感到困惑,只需转储$error变量并检查如何检索它。 即使验证通过但在上面的代码中失败了,也不会与验证确实失败的情况有所不同。

显然不知道您的表单字段是什么,但这应该可行。

这是使用others()方法添加条件查询的,如果相应的字段等于no,则字段值不应为no。

    $data = array(
        'field1' => 'no',
        'field2' => 'no'
    );

    $validator = Validator::make($data, array());
    $validator->sometimes('field1', 'not_in:no', function($input) {
        return $input->field2 == 'no';
    });
    $validator->sometimes('field2', 'not_in:no', function($input) {
        return $input->field1 == 'no';
    });

    if ($validator->fails()) {
        // will fail in this instance
        // changing one of the values in the $data array to yes (or anything else, obvs) will result in a pass
    } 

请注意,这仅适用于Laravel 4.2+

暂无
暂无

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

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