I am facing a problem with laravel custom validation message, here is what I have:
$rules = [
'first_name' => 'required|alpha|min:2',
'last_name' => 'required|alpha|min:2',
'email' => 'required|email|unique:users,email,' . Input::get('id') . ',id',
'password' => 'alpha_num|between:6,12|confirmed',
'password_confirmation' => 'alpha_num|between:6,12',
'address' => 'regex:/^[a-z0-9- ]+$/i|min:2',
'city' => 'alpha|min:2',
'state' => 'alpha|min:2|max:2',
'zip' => 'numeric|min:5|max:5',
'phone' => 'regex:/^\d{3}\-\d{3}\-\d{4}$/',
];
$messages = [
'unique' => 'The :attribute already been registered.',
'regex' => 'The :attribute number has to be formated : xxx-xxx-xxxx.',
];
Now if there is a problem with the address or the phone number since both have regex validation rule , the error message will be : The :attribute number has to be formated : xxx-xxx-xxxx, How could I have custom message for each different one ??
After checking if the request failed to pass validation, you may use the withErrors method to flash the error messages to the session. When using this method, the $errors variable will automatically be shared with your views after redirection, allowing you to easily display them back to the user.
You can make the code powerful by using the Laravel custom validation rule with parameters. This streamlines the flow between the logic and code wherever required. Laravel offers various convenient validation rules that can be applied to the data if values are specific to a database table.
To get the exact words to validate you can make use of Rule::in method available with laravel. Using Rule::in method whatever the values provided by this rule has to be matched otherwise it will fail.
Here is the way to do it , just instead of using 'regex' , use 'phone.regex'
$rules = [
'first_name' => 'required|alpha|min:2',
'last_name' => 'required|alpha|min:2',
'email' => 'required|email|unique:users,email,' . Input::get('id') . ',id',
'password' => 'alpha_num|between:6,12|confirmed',
'password_confirmation' => 'alpha_num|between:6,12',
'address' => 'regex:/^[a-z0-9- ]+$/i|min:2',
'city' => 'alpha|min:2',
'state' => 'alpha|min:2|max:2',
'zip' => 'numeric|min:5|max:5',
'phone' => 'regex:/^\d{3}\-\d{3}\-\d{4}$/',
];
$messages = [
'unique' => 'The :attribute already been registered.',
'phone.regex' => 'The :attribute number is invalid , accepted format: xxx-xxx-xxxx',
'address.regex' => 'The :attribute format is invalid.',
];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With