Search code examples
laravellaravel-validation

Laravel custom validation message for wildcard (*) dot notation


When defining validation for lets say form elements that have the same array name, we use the wildcard (*) dot-notation

Lets say you have a form as shown:

<input type="text" name="client_type[]" class="form-control" value="Panelist" readonly>
<input type="number" name="commission_percentage[]" class="form-control">

<input type="text" name="client_type[]" class="form-control" value="Non Panelist" readonly>
<input type="number" name="commission_percentage[]" class="form-control">

Inorder to validate the commission_percentage field, we would do this in a form request class:

public function rules()
{
   $rules = [];

   $rules['commission_percentage.*'] = 'required';

   return $rules;
}

From the form above, submitting it while empty would generate the following validation error message:

The commission_percentage.0 field is required. 
The commission_percentage.1 field is required

The validation error message would be repeated twice since the commission_percentage array from the form has 2 values. Now imagine a case where the array has multiple values, the validation error message would be repeated each and every time!

So the question is: Is there a workaround for this so that instead of the validation error message being repeated n number of times, we have one validation error message that will be output and represent all the items in the same array?

Thanks.


Solution

  • I think you can override the messages method in your form request and add a single message, for example:

    public function messages()
    {
        return [
            'commission_percentage.*' => 'Your field is required'
        ];
    }
    

    Then to use it in the view you should exclude it from the $errors->any() loop but to get it as a single error like this:

    @if ($errors->has('commission_percentage.*'))
        <div class="help-block">
            <ul role="alert">
               <li>{{ $errors->first('commission_percentage.*') }}</li>
            </ul>
        </div>
    @endif