Laravel 验证如果勾选了复选框,则需要输入文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38525613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:12:02  来源:igfitidea点击:

Laravel Validation If checkbox ticked then Input text is required?

laravellaravel-5laravel-5.2

提问by I'll-Be-Back

I have been reading Laravel validation documentation. I am not clear how to combine two rules.

我一直在阅读 Laravel 验证文档。我不清楚如何结合两个规则。

For example:

例如:

<input type="checkbox" name="has_login" value="1">

<input type="text" name="pin" value="">

If has_logincheckbox is ticked then Input text pinvalue is required.

如果has_login勾选复选框,pin则需要输入文本值。

If has_loginis not ticked then Input text pinis not required.

如果has_login未勾选,则pin不需要输入文本。

Laravel Validation:

Laravel 验证:

public function rules()
{
    return [
          'has_login' => 'accepted',
          'pin' => 'required',
    ];
}

回答by H H

Use required_with or required_if

使用 required_with 或 required_if

required_with:foo,bar

The field under validation must be present and not empty only if any of the other specified fields are present.

required_with:foo,bar

仅当存在任何其他指定字段时,验证中的字段必须存在且不能为空。

return [
      'has_login' => 'sometimes',
      'pin'       => 'required_with:has_login,on',
];

--

——

required_if:anotherfield,value

The field under validation must be present and not empty if the anotherfield field is equal to any value.

required_if:anotherfield,value

如果 anotherfield 字段等于任何值,则验证中的字段必须存在且不为空。

return [
      'has_login' => 'sometimes',
      'pin'       => 'required_if:has_login,on',
];

--

——

https://laravel.com/docs/5.2/validation

https://laravel.com/docs/5.2/validation

--

——

Also, if the checkbox has_loginis not checked, it will not send as part of the form submission

此外,如果has_login未选中复选框,则不会作为表单提交的一部分发送