Eem Jee
Eem Jee

Reputation: 1309

Laravel validation required_if is not working

I have the email and password fields in which I only want them to be required if the add_user field value is 1. This is my validation:

public function rules() {
    return [
        'add_user' => ['required'],
        'password' => ['required_if:add_user,1', 'min:8'],
        'email' => ['required_if:add_user,1', 'email', 'max:255'],
    ];
}

This one is not working, it always errors even if the value is 0. I fill out the add_user value using jquery. I have a drop down that if the user clicked from the options, add_user value is 0, but if thru input, value is 1. Values are correct but the validation isn't working. Can someone help me figure this out?

Upvotes: 0

Views: 1541

Answers (2)

Muhammad Shareyar
Muhammad Shareyar

Reputation: 822

We are checking two fields that are not dependent to each other means if user_id!=1 there will be some other validation on password and email so we need to check it by this way

     $rules = [
           'type' => 'required'
         ];

     $v = Validator::make(Input::all(),$rules);

     $v->sometimes('password', 'required|min:8', function($input) {
          return $input->type == '1';
     });

Here we make an instance of Validator where we checking password is required if user_id ==1 else we no need to validate it.

In Model you can do this.

 public function rules(){
    return [
      'user_id '     => 'required'
    ];
 }

 protected function getValidatorInstance() {
        $validator = parent::getValidatorInstance();
        $validator->sometimes('password', 'required|min:8', 
            function($input) {
            return $input->user_id== 1;
        });
        return $validator;
    }

Upvotes: 0

Eem Jee
Eem Jee

Reputation: 1309

Okay. Got it.

I added a nullable validation property and now it works.

return [
    'add_user' => ['required'],
    'password' => ['required_if:add_user,1', 'min:8', 'nullable'],
    'email' => ['required_if:add_user,1', 'email', 'max:255', 'nullable'],
];

Hope this will help someone, someday.

Upvotes: 2

Related Questions