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
Laravel Validation If checkbox ticked then Input text is required?
提问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_login
checkbox is ticked then Input text pin
value is required.
如果has_login
勾选复选框,pin
则需要输入文本值。
If has_login
is not ticked then Input text pin
is 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_login
is not checked, it will not send as part of the form submission
此外,如果has_login
未选中复选框,则不会作为表单提交的一部分发送