1
votes

I have a form that has some conditional logic that displays or hides each field. I only want to validate the fields that are shown. See the field list in my validation script below and imagine I hide the "phone" form field in using conditional logic in the view — I still want to validate the rest of the fields, but if "phone" validation is still there, the script fails and shows the error message saying "The phone number is required."

In Laravel 5, is there a way check if a form field exists or change whether it's required or not dynamically before or when validating the form?

Here's my validation code...

        $v = Validator::make(input()->all(), [
            'firstName' => 'required|Min:1|Max:80',
            'lastName'  => 'required|Min:1|Max:80',
            'address'  => 'required|Min:10|Max:80',
            'address2'  => 'Max:20',
            'city'  => 'required|Min:2|Max:80',
            'state'  => 'required|Min:2|Max:80',
            'zip'  => 'required|Min:5',
            'phone'  => 'required|regex:'.validPhoneRegex(),
        ]);
        if($v->fails())
        {
            return redirect()->back()->withErrors($v)->withInput(input()->all());
        }
2

2 Answers

1
votes

You can use the sometimes() method for that :

$v->sometimes('phone', 'required', function($input) {
    //Your condition here, the "required" validation on the "phone" field will
      only run if this returns true
});

You can then remove phone from your initial validation.

From the documentation :

Note: The $input parameter passed to your Closure will be an instance of Illuminate\Support\Fluent and may be used to access your input and files.

See documentation here

1
votes

The following validation rule should do the job:

'phone'  => 'sometimes|regex:'.validPhoneRegex(),