Custom Laravel validation messages

隐身守侯 提交于 2019-12-04 08:05:00

问题


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?


回答1:


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);



回答2:


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!'
    ]);
}



回答3:


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




回答4:


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

$messages = [
  'required'  => 'Harap bagian :attribute di isi.',
  'unique'    => ':attribute sudah digunakan'
];

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


来源:https://stackoverflow.com/questions/45007905/custom-laravel-validation-messages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!