Laravel - 验证 - 如果字段为空则要求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38893967/
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 - Require if field is null
提问by Eliya Cohen
Let's say I have this html code:
假设我有这个 html 代码:
<input type="email" name="email">
<input type="password" name="password">
Or this:
或这个:
<input type="hidden" name="user_id" value="1">
(If the user is logged in, only the user_id
field will be shown. else - the credentials fields).
(如果用户已登录,则只会显示该user_id
字段。否则 - 凭据字段)。
When I create a request, there's a validation that checks the user. if the field user_id
exists (i.e if user_id
exists in the users table), then there's no need to require email
and password
inputs. If there's no user_id
, then the email
and password
fields will be required.
当我创建一个请求时,有一个检查用户的验证。如果该字段user_id
存在(即如果user_id
存在于用户表中),则不需要要求email
和password
输入。如果没有user_id
,则email
和password
字段将是必需的。
In other words, I want to do something like this:
换句话说,我想做这样的事情:
public function rules()
{
return [
'user_id' => 'exists:users,id',
'email' => 'required_if_null:user_id|email|...',
'password' => 'required_if_null:user_id|...'
];
}
回答by Eliya Cohen
After reading the Validation docs again, I found a solution. I just needed to do the opposite, using the required_without
validation:
再次阅读验证文档后,我找到了解决方案。我只需要做相反的事情,使用required_without
验证:
public function rules()
{
return [
'user_id' => 'exists:users,id',
'email' => 'required_without:user_id|email|unique:users,email',
'password' => 'required_without:user_id',
}