0

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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;
    }

1 Comment

Check i have made some changes to it,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.