Laravel 5.5 validate with custom messages

余生颓废 提交于 2020-08-24 10:42:48

问题


I'm working on a pw change form in my laravel app. I want to use the validator with custom error messages.

My code looks like this:

  $rules = [
    'username' => 'required|max:255',
    'oldpassword' => 'required|max:255',
    'newpassword' => 'required|min:6|max:255|alpha_num',
    'newpasswordagain' => 'required|same:newpassword',
  ];
  $messages = [
     'username.required' => Lang::get('userpasschange.usernamerequired'),
     'username.max:255' => Lang::get('userpasschange.usernamemax255'),
     'oldpassword.required' => Lang::get('userpasschange.oldpasswordrequired'),
     'oldpassword.max:255' => Lang::get('userpasschange.oldpasswordmax255'),
     'newpassword.required' => Lang::get('userpasschange.newpasswordrequired'),
     'newpassword.min:6' => Lang::get('userpasschange.newpasswordmin6'),
     'newpassword.max:255' => Lang::get('userpasschange.newpasswordmax255'),
     'newpassword.alpha_num' => Lang::get('userpasschange.newpasswordalpha_num'),
     'newpasswordagain.required' => Lang::get('userpasschange.newpasswordagainrequired'),
     'newpasswordagain.same:newpassword' => Lang::get('userpasschange.newpasswordagainsamenewpassword'),
 ];

  $validator = Validator::make($request->all(), $rules, $messages);
  $validator->setCustomMessages($messages);

  Log::debug("custommessages: " . json_encode($messages));
  Log::debug("messages: " . json_encode($validator->messages()));

In the log custommessages is shows my custom msgs, but in the next line there is the original messages.

I'm working from the official doc.

Have anybody meet this problem?

Thx for the answers in advance!


回答1:


A rewrite and the recommended way of doing it. Manual for reference https://laravel.com/docs/5.5/validation#creating-form-requests

Use requests files.

  1. run php artisan make:request UpdateUserPasswordRequest
  2. Write the request file

Edit feb 2020: in the latest version of Laravel in the authorize method the global auth() object can be used instead of \Auth so \Auth::check() will become auth()->check(). Both still work and will update if something is removed from the framework

namespace App\Http\Requests;

class UpdateUserPasswordRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        // only allow updates if the user is logged in
        return \Auth::check();
        // edit you can now replace this with return auth()->check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'username' => 'required|max:255',
            'oldpassword' => 'required|max:255',
            'newpassword' => 'required|min:6|max:255|alpha_num',
            'newpasswordagain' => 'required|same:newpassword',
        ];
    }

    /**
     * Get the validation attributes that apply to the request.
     *
     * @return array
     */
    public function attributes()
    {
        return [
            'username'            => trans('userpasschange.username'),
            'oldpassword'             => trans('userpasschange.oldpassword'),
            'newpassword'             => trans('userpasschange.newpassword'),
            'newpasswordagain'       => trans('userpasschange.newpasswordagain'),
        ];
    }

    /**
     * Get the validation messages that apply to the request.
     *
     * @return array
     */
    public function messages()
    {
// use trans instead on Lang 
        return [
     'username.required' => Lang::get('userpasschange.usernamerequired'),
     'oldpassword.required' => Lang::get('userpasschange.oldpasswordrequired'),
     'oldpassword.max' => Lang::get('userpasschange.oldpasswordmax255'),
     'newpassword.required' => Lang::get('userpasschange.newpasswordrequired'),
     'newpassword.min' => Lang::get('userpasschange.newpasswordmin6'),
     'newpassword.max' => Lang::get('userpasschange.newpasswordmax255'),
     'newpassword.alpha_num' =>Lang::get('userpasschange.newpasswordalpha_num'),
     'newpasswordagain.required' => Lang::get('userpasschange.newpasswordagainrequired'),
     'newpasswordagain.same:newpassword' => Lang::get('userpasschange.newpasswordagainsamenewpassword'),
      'username.max' => 'The :attribute field must  have under 255 chars',
        ];
    }
  1. In UserController
<?php namespace App\Http\Controllers;


// VALIDATION: change the requests to match your own file names if you need form validation
use App\Http\Requests\UpdateUserPasswordRequest as ChangePassRequest;
//etc

class UserCrudController extends Controller
{
public function chnagePassword(ChangePassRequest $request)
{
 // save new pass since it passed validation if we got here
}
}



回答2:


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

$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...




回答3:


After you've indicated the messages in Validator::make

$validator = Validator::make($request->all(), $rules, $messages);

you shouldn't indicate them again

$validator->setCustomMessages($messages); // don't do that

NOTE

The better way to use Request validation is to move them to another file




回答4:


$messages = [
     'username.required' => Lang::get('userpasschange.usernamerequired'),
     'username.max' => Lang::get('userpasschange.usernamemax255'),
     'oldpassword.required' => Lang::get('userpasschange.oldpasswordrequired'),
     'oldpassword.max' => Lang::get('userpasschange.oldpasswordmax255'),
     'newpassword.required' => Lang::get('userpasschange.newpasswordrequired'),
     'newpassword.min' => Lang::get('userpasschange.newpasswordmin6'),
     'newpassword.max' => Lang::get('userpasschange.newpasswordmax255'),
     'newpassword.alpha_num' => Lang::get('userpasschange.newpasswordalpha_num'),
     'newpasswordagain.required' => Lang::get('userpasschange.newpasswordagainrequired'),
     'newpasswordagain.same:newpassword' => Lang::get('userpasschange.newpasswordagainsamenewpassword'),
 ];

Try to dont use this :255 and :6 endings.


Wrong:

'username.max:255' => Lang::get('userpasschange.usernamemax255'),

Correct:

'username.max' => Lang::get('userpasschange.usernamemax255'),


来源:https://stackoverflow.com/questions/49432025/laravel-5-5-validate-with-custom-messages

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