Laravel validation messages contain "validation." instead of custom error message - laravel

I have a function that does some validation. Instead of $errors->get(key) returning the custom error messages I've defined, I'm getting the validation rule name. For example, if I use an email that's not unique:
$messages = [
'new_email.required' => 'Your new email address is required.',
'new_email:unique' => 'That email is already in use.',
'current_password|required' => 'Your current password must be provided.'
];
$rules = [
'new_email' => 'required|email|unique:users,email,' . $user->id,
'current_password' => 'required',
];
$validator = Validator::make($request->all(), $rules, $messages); // <-- custom error messages passed in here
if ($validator->fails()) {
$errors = $validator->errors();
if ($errors->has('new_email')) {
$msg = $errors->get('new_email'); // $msg contains ['validation.unique'] instead of ['That email is already in use.']
...
}
}
$errors->get('new_email') returns ['validation.unique'] instead of the custom error message in the array that's passed as the 3rd parameter to Validator::make. How can I get the custom error message instead of the validation rule that has been broken by the request?
There are some similar questions to this, but all the answers seem to focus on the resource/lang/xx/validation.php file missing or something like that. I'm not using those localization features at all.

Based on the documentation you should set your message with a string between property and validation rule.
$messages = [
'new_email.unique' => 'That email is already in use.',
];

Related

How to make 2 different Laravel Validation messages for the same rule that has 2 different arguments?

Hello I have Laravel validation request with these rules
public function rules()
{
return [
'email' => 'unique:users,email|required|unique:invitations,email',
'name' => 'string|required',
];
}
I want that "unique:users,email" would display one message and "unique:invitations,email" display other message. How to do that?
'unique:users,email' => 'This E-Mail address is already registered.',
'unique:invitations,email' => 'Invitation to this E-Mail address is already sent.',
It always returns default message for "unique" rule.
'unique' => 'The :attribute has already been taken.',
I am not sure if this will work but can you try these
public function messages()
{
return [
'unique:users,email' => 'This E-Mail address is already registered.',
'unique:invitations,email' => 'Invitation to this E-Mail address is already sent.',
//or
'email.unique:users,emai' => 'This E-Mail address is already registered.',
'email.unique:invitations,email' => 'Invitation to this E-Mail address is
//you may even try it without the ,fieldname
'email.unique:users' => ''
];
}
Try to define like
'email.unique:users,emai' => ....,
'email.unique:invitations,emai' => ....,

Validate POST request Laravel?

I validate POST request like:
$validator = Validator::make($request->all(), [
"id.*" => 'required|integer'
]);
if ($validator->fails()) {
return response()->json($validator->errors, 400);
}
echo "Ok";
When I send request without parameter id it skips validation and returns echo "Ok";.
Why validation does not work?
If you expect id is array of integers you should update validation rules like this:
$validator = Validator::make($request->all(), [
"id" => 'required|array',
"id.*" => 'integer'
]);
First know when using $request->validate(); when it fail exceptions are raised!
And they are automatically handled by laravel. If it's a get, or a normal post form, then the process will redirect back to the form.
To note, when using the validate method during an AJAX request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.
If you want to not have such an automatic behavior, create manually a validator, then you can check with ->fails() method, as the example show bellow. That's can be handful in a lot of situations.
<?php
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
// Store the blog post...
}
}
And there is no better then the doc itself: https://laravel.com/docs/5.7/validation
there is a lot of options, to personalize our validation process.

Laravel Array Validation Message Value

For array validation messages, is there a way to display the value as opposed to the attribute? Doing so without using a custom validator.
Example:
$messages = [
‘*' => ':value is invalid.’
]
This would output something like "email#address is invalid".
Thanks for your help!
In case anyone is still looking with the latest of Laravel versions, the answer is to use the :input parameter in your message output:
'between' => 'The :attribute value :input is not between :min - :max.'
Docs: https://laravel.com/docs/5.7/validation#custom-error-messages
To access the index for the array validation I simply iterate over the elements I'm trying to validate instead of using the * wildcard.
public function messages()
{
$messages = [];
foreach($this->emails as $key => $email) {
$messages[$key] = $email . ' is an invalid email address.';
}
return $messages;
}
Hope this helps anyone who is having the same problem.
For fully custom strings you can pass custom messages as the third argument to the Validator::make() method. If you need only generic descriptors you can use some built place-holders such as :attribute, :size, or :values
For example:
$messages = ['required' => 'The :attribute field is required.'];
$validator = Validator::make($input, $rules, $messages);
:attribute will be replaced by the actual name of the field under validation.
More info can be found here.

Do custom error messages in Laravel 4.2

I'm new in Larvel 4.2 here! How do I do a custom error messages in Laravel 4.2? And where do I put these codes? I've been using the defaults and I kind of wanted to use my own.
Did you try something? http://laravel.com/docs/4.2/validation#custom-error-messages
Did you use Google? Check the documentation (official) it has everything. Be less lazy.
$messages = array(
'required' => 'The :attribute field is required.',
);
$validator = Validator::make($input, $rules, $messages);
To add to the answer given by slick, here is how you could use it in a real example of a store function inside a controller:
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'id1' => 'required|between:60,512',
'id2' => 'required|between:60,512',
'id3' => 'required|unique:table',
], [
'id1.required' => 'The first field is empty!',
'id2.required' => 'The second field is empty!',
'id3.required' => 'The third field is empty!',
'id1.between' => 'The first field must be between :min - :max characters long.',
'id2.between' => 'The second answer must be between :min - :max characters long.',
'id3.unique' => 'The third field must be unique in the table.',
]);
if ($validator->fails()) {
return Redirect::back()
->withErrors($validator)
->withInput();
}
//... Do something like store the data entered in to the form
}
Where the id should be the ID of the field in the form you want to validate.
You can check out all the rules you can use here.

How to pass external validation through model labels and error messages?

In Kohana 3.2, passing external validation on Model_User upon save, why won't the correct message show?
I have user.php in application/messages/models which reads and translates fine for the "internal" data, while _external.php resides in application/messages/models/user.
When _external data is invalid, the default error message from Kohana is shown, and thus not correctly translated or given the correct labels from Model_User.
Edit, with code:
// We have $_POST, register a new user
$user = ORM::factory('user');
/*
* Here a bunch of variables are set
*/
$extra = Validation::factory($_POST)->
rule('email', 'email')-> // I run this check, because in my Model_User, email is filtered through Encrypt
rule('name', 'not_empty'); // Same goes for name
try {
$user->save($extra);
} catch (ORM_Validation_Exception $e) {
$this->template->errors = $e->errors('models', true);
}
So, when $extra variables don't match the rule, I would like to get nice error messages from application/messages/models/user/_external.php, which looks like:
return array(
'email' => array(
'email' => ':field must be a valid email address',
),
'name' => array(
'not_empty' => ':field must not be empty',
),
);
Also, it would be nice if :field was fetched from Model_User "labels".
You need to put _external.php next to your user.php in the messages/models directory, not in the messages/models/user directory. I had the same problem, it worked for me.

Resources