2

When customising Laravel 5.7 validation attributes, is it possible to include wildcards in the attribute names? I can't determine the correct way to indicate a wildcard here.

I have a contacts page which lists the details of a particular contact including all of their phone numbers and emails. From this page you can edit each of these, and add new ones. As such I've used a foreach statement to display each of these and included their id numbers in the form field names, ie:

  • phone_areacode_{{ $number->id }}
  • phone_number_{{ $number->id }}
  • phone_extension_{{ $number->id }}

This makes their names unique and means I can display the error messages relevant only to the specific number or email being edited when validation fails. However, the error messages that display include the number so I get things like "The phone areacode 10 format is invalid." or "The phone number 27 may not be greater than 20 characters."

Is there a way to use wildcards in the attribute names when defining them in the validation language file? Basically I'd like to be able to do this:

'attributes' => [
  'phone_areacode_*.*' => 'phone areacode',
],

If not, how can I define the attribute names in the @update method of my controller?

1
  • Any solution yet? Commented Mar 14, 2020 at 18:27

2 Answers 2

2

Post values using arrays/objects, and specify validation rules/lang using dot notation:

Example POST data:

{
  "phone": {
    "ID1234": {
      "areacode": "123",
      "number": "1231234",
      "extension": "1"
    }
  }
}

Example HTML form (equivalent to POST data above):

<form action="?" method="post">
  <input name="phone[ID1234][areacode]" />
  <input name="phone[ID1234][number]" />
  <input name="phone[ID1234][extension]" />

  <input type="submit">Submit</input>
</form>

Example validation:

$validator = Validator::make($request->all(), [
  'phone.*.areacode': 'required',
  'phone.*.number': 'required',
  'phone.*.extension': 'required',
]);

Example lang file:

return [
  'attributes' => [
    'phone.*.areacode': 'phone area code',
    'phone.*.number': 'phone number',
    'phone.*.extension': 'phone extension',
  ],
]);
Sign up to request clarification or add additional context in comments.

Comments

-1

do you try this way it's from Laravel documentation

'custom' => [
        'attribute-name' => [
            'rule-name' => 'custom-message',
        ],
    ],

1 Comment

That won't work either; its the same problem I'm already having. Where it reads 'attribute-name', I need THAT to contain the wildcard (eg. 'attribute-name_%')

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.