1

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 Answers 2

1

The following validation rule should do the job:

'phone'  => 'sometimes|regex:'.validPhoneRegex(),
Sign up to request clarification or add additional context in comments.

3 Comments

This is a much simpler way to do it, I saw it in the documentation but for some reason misread didn't think it would work
Brilliant! That's exactly what I needed. Thank you.
btw, my rep isn't high enough yet otherwise my up vote would show :) thanks again!
1

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

Comments

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.