1

In Laravel you can make a custom messages for validators. But I found that the prepared messages are little bit wrong. With before and after validation rules, the parameter is converted with strtotime like that said in the documentation.

So if I set rule 'expires' => 'before:+1 year' the rule is working and correct. But if the user inputs a wrong value, Laravel prints the message like that:

The expires must be a date before +1 year

This message is very unclear for the average client. I was expected that the message will be converted with the strtotime also.

There is a clean way to print more clear error message?

2 Answers 2

0

You can override the validation messages with a custom ones if you want to.

In the Form Request class, add the following method and change the messages like so:

public function messages()
{
    return [
        // 'fieldname.rulename' => 'Custom message goes here.'
        'email.required' => 'Er, you forgot your email address!',
        'email.unique' => 'Email already taken m8',
    ];
}

Update:

If you want to change the global messages, you can open the validation.php file inside resources/lang/en/validation.php and edit the message there.

Sign up to request clarification or add additional context in comments.

7 Comments

But instead of doing that for each validator, can I do it for after/before rules by default?
yeah, I don't see why not, these are just examples to give you the idea. Just change the field name and rule name and you should be good to go.
I understand that, but I have a lot of validators with before and after, I don't want to change them all manually....
What about a foreach loop?
I don't understand how foreach loop will help me. I have a lot of validatiors in different classes. I want to change the after and before message so they will be calculated with strtotime and I want to do it globally.
|
0

You can user AppServiceProvider.php
and you can write your new validation rule there and set your error message in validation.php file
/app/Providers/AppServiceProvider.php
/resources/lang/en/validation.php

Ex:

    Validator::extend('before_equal', function ($attribute, $value, $parameters) {
        return strtotime(Input::get($parameters[0])) >= strtotime($value);
    });

and the message is

    'before_equal' => 'The :attribute field is only accept date format before or equal to end date',        

Please try this and you can alter this to based on your require.

Comments

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.