I have a form input with an email
-field, email_confirmation
-field and then fname
- & lname
-fields that can be cloned using javascript so multiple names can be added.
The input variables are consequently named email
, email_confirmation
and persons[0][fname]
+ persons[0][lname]
respectively (with incrementing index 0 if multiple names were supplied).
I'm trying to set custom validation messages for an array input:
in RegisterRequest.php
public function rules()
{
$rules = array();
foreach ($this->input('persons') as $index => $person) {
$fname = 'persons.' . $index . '.fname';
$lname = 'persons.' . $index . '.lname';
$rules[$fname] = 'sometimes|required_with:'.$lname.'|max:25';
$rules[$lname] = 'sometimes|required_with:'.$fname.'|max:35';
}
return array_merge([
'email' => 'required|confirmed|email',
'email_confirmation' => 'required',
], $rules);
}
public function messages()
{
$array = array(
'email.required' => 'Je e-mailadres is verplicht.',
'email.email' => 'Dit is geen geldig e-mailadres',
'email.confirmed' => 'E-mailadressen komen niet overeen.',
'email_confirmation.required' => 'Bevestig je e-mailadres.',
);
foreach ($this->input('persons') as $index => $person) {
$fname = 'persons.' . $index . '.fname';
$lname = 'persons.' . $index . '.lname';
$array[$fname.'.max:25'] = 'Je kan maximaal 25 karakters ingeven.';
$array[$lname.'.max:35'] = 'Je kan maximaal 35 karakters ingeven.';
$array[$fname.'.required_with:' . $lname] = 'Vul de voornaam in.';
$array[$lname.'.required_with:' .$fname] = 'Vul de achternaam in.';
}
return $array;
}
Email error message is correctly being displayed, but unfortunately the messages for the input array don't... Any ideas how to achieve this? I think the problem lies in the fact that validation messages are defined using the dot rule (attribute.rule
), but my input array attribute also consists of dots...
For the custom messages you don't specify the actual validation rule with parameters. Just it's name:
$array[$fname.'.max'] = 'Je kan maximaal 25 karakters ingeven.';
$array[$lname.'.max'] = 'Je kan maximaal 35 karakters ingeven.';
$array[$fname.'.required_with'] = 'Vul de voornaam in.';
$array[$lname.'.required_with'] = 'Vul de achternaam in.';
For the max
validation you may use the :max
placeholder inside your message to retrieve the number that's passed to the rule:
$array[$fname.'.max'] = 'Je kan maximaal :max karakters ingeven.';
$array[$lname.'.max'] = 'Je kan maximaal :max karakters ingeven.';