Victori
Victori

Reputation: 359

Adding a check for validator if field is not empty

I have a validator for users to update their profile, and on the same page the user can change their password. Although, I do not want to run a check if all the 3 fields (current password, new / confirmed) is empty.

Is there a way I can add in a custom check in the Validator::makeand check, or add to the validator and add the return with errors page?

$validator = Validator::make($request->all(), [
        'first_name' => 'required|max:191',
        'last_name' => 'required|max:191',
        'email' => 'required|email|max:191'
      ]);

example 3 field are empty and wouldnt be a problem, although what if they're filled out... can I append to this for check

example

if ($request->new_password) {
$validator .= array('new_password' => 'required');
}

my last solution would be to have two validators... would that work?

Upvotes: 0

Views: 53

Answers (1)

ndrwnaguib
ndrwnaguib

Reputation: 6135

You can accomplish this by adding sometimes to your rule list. sometimes runs validation checks against a field only if that field is present in the input array. As an exmaple,

$v = Validator::make($data, [
'email' => 'sometimes|required|email',
]);

For more rules options you can refer to Laravel Validator Documentation.

Upvotes: 1

Related Questions