简体   繁体   中英

Laravel - Validation - Require if field is null

Let's say I have this html code:

<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).

When I create a request, there's a validation that checks the user. if the field user_id exists (ie 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.

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|...'
    ];
}

After reading the Validation docs again, I found a solution. I just needed to do the opposite, using the required_without validation:

public function rules()
{
    return [
        'user_id'       => 'exists:users,id',
        'email'         => 'required_without:user_id|email|unique:users,email',
        'password'      => 'required_without:user_id',
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM