1

I want to insert my validation custom messages inside the validate function as shown:

public function postLogin(Request $request)
    {
        $rulesemail=['required'=>'Este campo es requerido.'];
        $rulespassword=['min'=>'Debe teclear al menos :min caracteres','required'=>'Favor de teclear su contraseña'];
        $this->validate($request, [
            'email' => 'required|email|max:60', 'password' => 'required|min:6'],$rulespassword
        );

But i can't get it to work. Any ideas?

0

2 Answers 2

1

You can't with the default validate() from the ValidatesRequests trait.

However you can override the function in your base controller to change that:

public function validate(Request $request, array $rules, array $messages = array())
{
    $validator = $this->getValidationFactory()->make($request->all(), $rules, $messages);

    if ($validator->fails())
    {
        $this->throwValidationException($request, $validator);
    }
}

And then simply pass the custom messages as third parameter:

$rulesemail=['required'=>'Este campo es requerido.'];
$messages=['min'=>'Debe teclear al menos :min caracteres','required'=>'Favor de teclear su contraseña'];
$this->validate($request, [
    'email' => 'required|email|max:60',
    'password' => 'required|min:6'
], $messages);

Remember that you can also globally define validation messages in a language file. This file is usually located at resources/lang/xx/validation.php

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

3 Comments

Where exactly is ValidatesRequests?
Illuminate\Foundation\Validation\ValidatesRequests that's the trait where the validates() method comes from. It should be included with use in the default base controller App\Http\Controllers\Controller
i saw this same question a few days ago on laravel forum
0

The validate() method accepts 3 parameters:

Request $request, [$errors], [$messages]

Here's an example of how to customise the error message for a validation condition:

    $this->validate(
        $request,
        [
            'first_name'=> 'required',
            'last_name'=> 'required',
            'email' => 'email',
            'date_of_birth' => 'date_format:"Y-m-d"'
        ],
        [
            'date_format' => 'DOB'
        ]
    );

PHPStorm provides useful tooltip to instantly see the method options.

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.