mardi 24 mars 2020

Refactor and Optimize Laravel validation rules (required_with)

I have a form whose number of inputs is flexible based on the number of rows of users.

| row |  FullName  |  Phone    |    Email   |
|------------------------------------------ |
|  1  |    Alex    |     06    |   a@a.com  |
|------------------------------------------ |
|  2  |    Bob     |    968    |            |
|------------------------------------------ |
|  3  |            |           |   j@j.com  |
---------------------------------------------
 _____________________
| Add new User Button |
 ---------------------

When any input of each user filled, other inputs of those user are required.

For ex: here we have error for row 2 because FullName and Phone are filled but Email is empty

or

Error for row 3 because FullName and Phone are empty but Email is filled.

So I write validation rule for that as below:

        $validator = Validator::make($request->all(), [
            'User.*.FullName' => 'required_with:User.*.Phone | required_with:User.*.Email',
            'User.*.Phone' => 'required_with:User.*.FullName | required_with:User.*.Email',
            'User.*.Email' => 'required_with:User.*.FullName | required_with:User.*.Phone',
        ], $this->messages());

The number of input parameters for each user is large, which I have listed here 3 cases (FullName,Phone,Email).

If I write validations like above the code is messy. How to refactor this code or any idea for these type of validation?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire