我正在将Laravel用于一个项目,并想知道如何验证我面临的特定场景。如果可能的话,我想用Laravel的原生功能来做到这一点?
我有一个表单,它有两个问题(作为下拉列表),答案可以是是或否,但是如果两个下拉列表都等于否,它应该抛出验证错误,但它们都可以是。
我已经检查了 laravel 文档,但不确定在这里应用什么规则,如果有可以使用的规则?在这种情况下,我需要编写自己的规则吗?
非常简单:
假设两个字段名称分别是 Foo 和 bar。
然后:
// 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
var 并检查如何检索它。 即使验证通过但在上面的代码中失败,它也不会与验证失败时发生的情况有任何区别。
显然不知道你的表单字段叫什么,但这应该可以工作。
这是使用 sometimes() 方法添加一个条件查询,如果相应的字段等于 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
}
请注意,这仅适用于Laravel4.2 +。