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

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

Laravel - Validation - Require if field is null

phpvalidationlaravelrequire

提问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_idfield 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_idexists (i.e if user_idexists in the users table), then there's no need to require emailand passwordinputs. If there's no user_id, then the emailand passwordfields will be required.

当我创建一个请求时,有一个检查用户的验证。如果该字段user_id存在(即如果user_id存在于用户表中),则不需要要求emailpassword输入。如果没有user_id,则emailpassword字段将是必需的。

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_withoutvalidation:

再次阅读验证文档后,我找到了解决方案。我只需要做相反的事情,使用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',
}