Custom Laravel validation messages

PhpLaravelLaravel Validation

Php Problem Overview


I'm trying to create customized messages for validation in Laravel 5. Here is what I have tried so far:

$messages = [
    'required' 	=> 'Harap bagian :attribute di isi.',
    'unique' 	=> ':attribute sudah digunakan',
];
$validator = Validator::make($request->all(), [
    'username' => array('required','unique:Userlogin,username'),
    'password' => 'required',
    'email'    => array('required','unique:Userlogin,email'),$messages
]);

if ($validator->fails()) { 
	return redirect('/')
       	->withErrors($validator) // send back all errors to the login form
        ->withInput();
} else {
	return redirect('/')
        ->with('status', 'Kami sudah mengirimkan email, silahkan di konfirmasi');	
}	

But it's not working. The message is still the same as the default one. How can I fix this, so that I can use my custom messages?

Php Solutions


Solution 1 - Php

Laravel 5.7.*

Also You can try something like this. For me is the easiest way to make custom messages in methods when you want to validate requests:

public function store()
{
    request()->validate([
        'file' => 'required',
        'type' => 'required'
    ],
    [
        'file.required' => 'You have to choose the file!',
        'type.required' => 'You have to choose type of the file!'
    ]);
}

Solution 2 - Php

If you use $this->validate() simplest one, then you should write code something like this..

$rules = [
        'name' => 'required',
        'email' => 'required|email',
        'message' => 'required|max:250',
    ];

    $customMessages = [
        'required' => 'The :attribute field is required.'
    ];

    $this->validate($request, $rules, $customMessages);

Solution 3 - Php

You can provide custom message like :

$rules = array(
            'URL' => 'required|url'
        );    
$messages = array(
                'URL.required' => 'URL is required.'
            );
$validator = Validator::make( $request->all(), $rules, $messages );

if ( $validator->fails() ) 
{
    return [
        'success' => 0, 
        'message' => $validator->errors()->first()
    ];
}

or

The way you have tried, you missed Validator::replacer(), to replace the :variable

Validator::replacer('custom_validation_rule', function($message, $attribute, $rule, $parameters){
    return str_replace(':foo', $parameters[0], $message);
});

You can read more from here and replacer from here

Solution 4 - Php

For Laravel 8.x, 7.x, 6.x
With the custom rule defined, you might use it in your controller validation like so :

$validatedData = $request->validate([
       'f_name' => 'required|min:8',
       'l_name' => 'required',
   ],
   [
    'f_name.required'=> 'Your First Name is Required', // custom message
    'f_name.min'=> 'First Name Should be Minimum of 8 Character', // custom message
    'l_name.required'=> 'Your Last Name is Required' // custom message
   ]
);

For localization you can use :

['f_name.required'=> trans('user.your first name is required'],

Hope this helps...

Solution 5 - Php

$rules = [
  'username' => 'required,unique:Userlogin,username',
  'password' => 'required',
  'email'    => 'required,unique:Userlogin,email'
];

$messages = [
  'required'  => 'The :attribute field is required.',
  'unique'    => ':attribute is already used'
];

$request->validate($rules,$messages);
//only if validation success code below will be executed

Solution 6 - Php

//Here is the shortest way of doing it.
 $request->validate([
     'username' => 'required|unique:Userlogin,username',
     'password' => 'required',
     'email'    => 'required|unique:Userlogin,email'
 ],
 [
     'required'  => 'The :attribute field is required.',
     'unique'    => ':attribute is already used'
 ]);
//The code below will be executed only if validation is correct.

Solution 7 - Php

You can also use the methods setAttributeNames() and setCustomMessages(), like this:

$validation = Validator::make($this->input, static::$rules);

$attributeNames = array(
    'email' => 'E-mail',
    'password' => 'Password'
);

$messages = [
    'email.exists' => 'No user was found with this e-mail address'
];

$validation->setAttributeNames($attributeNames);
$validation->setCustomMessages($messages);

Solution 8 - Php

For those who didn't get this issue resolve (tested on Laravel 8.x):

$validated = Validator::make($request->all(),[
   'code' => 'required|numeric'
  ],
  [
    'code.required'=> 'Code is Required', // custom message
    'code.numeric'=> 'Code must be Number', // custom message       
   ]
);

//Check the validation
if ($validated->fails())
{        
    return $validated->errors();
}

Solution 9 - Php

    $rules = [
        'name' => 'required',
        'email' => 'required|email',
        'message' => 'required|max:250',
    ];

    $customMessages = [
        'required' => 'The :attribute field is required.',
        'max' => 'The :attribute field is may not be greater than :max.'
    ];

    $this->validate($request, $rules, $customMessages);

Solution 10 - Php

run below command to create a custom rule on Laravel
ı assuming that name is CustomRule

php artisan make:rule CustomRule

and as a result, the command was created such as PHP code

>if required keyword hasn't on Rules,That rule will not work

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class CustomRule implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        //return  true or false
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The validation error message.';
    }
}


and came time using that first, we should create a request class if we have not

php artisan make:request CustomRequest

CustomRequest.php

<?php


namespace App\Http\Requests\Payment;

use App\Rules\CustomRule;
use Illuminate\Foundation\Http\FormRequest;

class CustomRequest extends FormRequest
{


    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules(): array
    {
        return [
            'custom' => ['required', new CustomRule()],
        ];
    }

    /**
     * @return array|string[]
     */
    public function messages(): array
    {
        return [
            'custom.required' => ':attribute can not be empty.',
        ];
    }
}

and on your controller, you should inject custom requests to the controller

your controller method

class FooController
{
    public function bar(CustomRequest $request)
    {
        
    }
}

Solution 11 - Php

In the case you are using Request as a separate file:

 public function rules()
 {
    return [
        'preparation_method' => 'required|string',
    ];
 }

public function messages()
{
    return [
        'preparation_method.required' => 'Description is required',
    ];
}

Tested out in Laravel 6+

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYVS1102View Question on Stackoverflow
Solution 1 - PhpJankyzView Answer on Stackoverflow
Solution 2 - PhpZedex7View Answer on Stackoverflow
Solution 3 - PhpJigar ShahView Answer on Stackoverflow
Solution 4 - PhpstaView Answer on Stackoverflow
Solution 5 - PhppgronoView Answer on Stackoverflow
Solution 6 - PhpKaleem ShoukatView Answer on Stackoverflow
Solution 7 - PhpBruno SilvaView Answer on Stackoverflow
Solution 8 - Phpvahid sabetView Answer on Stackoverflow
Solution 9 - PhpSK TokeView Answer on Stackoverflow
Solution 10 - Phpdılo sürücüView Answer on Stackoverflow
Solution 11 - PhpAlex StView Answer on Stackoverflow