【问题标题】:Laravel 5.5 validate with custom messagesLaravel 5.5 使用自定义消息进行验证
【发布时间】:2022-02-11 21:39:22
【问题描述】:

我正在我的 laravel 应用程序中处理 pw 更改表单。我想使用带有自定义错误消息的验证器。

我的代码如下所示:

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

在日志 custommessages 中显示了我的自定义消息,但在下一行中有原始 messages

我在 official doc 工作。

有人遇到过这个问题吗?

谢谢提前回答!

【问题讨论】:

  • 手册中有laravel.com/docs/5.6/validation#customizing-the-error-messages 我不太明白你使用它们的方式。你能用类更新代码吗?我不太明白你是如何调用验证器的。在我看来,你在那里调用了 wring 验证器
  • @Indra 我按照它所说的那样做了一个函数(在控制器中),但没有任何改变。我应该将该函数移动到另一个文件吗?
  • @Indra 我更新了问题。
  • 你需要通过运行 php artisan make:request RequestName 来创建一个请求文件并在那里添加所有的逻辑。然后在控制器中使用 use 添加请求文件,并在方法中执行类似 function update(YourRequestName $resquest){ // function logic}
  • @Indra 我收到拒绝访问错误。 AccessDeniedHttpException This action is unauthorized.我应该在哪里注册这个新请求?

标签: laravel laravel-5 laravel-5.5


【解决方案1】:

重写和推荐的方法。 参考手册https://laravel.com/docs/5.5/validation#creating-form-requests

使用请求文件。

  1. 运行php artisan make:request UpdateUserPasswordRequest
  2. 编写请求文件

2020 年 2 月编辑:在最新版本的 Laravel 中,在授权方法中,可以使用全局 auth() 对象代替 \Auth,因此 \Auth::check() 将变为 auth()->check()。两者仍然有效,如果从框架中删除某些内容,它们会更新

 <?php
     
     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();
              // In laravel 8 use 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. 在用户控制器中
<?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
}
}

【讨论】:

  • 如果不是答案,则不应添加为答案。此外,OP 链接到 Laravel 5.5 文档。
  • 谢谢!我给它一个机会
  • @Camilo 它确实以非常好的方式解决了这个问题。而且5.5和5.6完全一样
  • @LakiGeri 如果您仍有问题,请告诉我
  • @Indra 非常感谢您的帮助!正如你所展示的,我提出了一个要求。属性运行良好,但消息不.. 所以我删除了 lang/en/validation.php 所以结果'validation.min.string' :D .. 所以消息是'stuborn'。我将翻译validation.php,它会解决我的问题。我要再次感谢你,我从中吸取了教训。 :)
【解决方案2】:

对于 Laravel 7.x6.x5.x
定义自定义规则后,您可以在控制器验证中使用它,例如:

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

对于本地化,您可以使用:

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

希望这会有所帮助...

【讨论】:

    【解决方案3】:

    Validator::make中指出消息后

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

    你不应该再次指出它们

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

    注意

    使用请求验证的更好方法是移动them to another file

    【讨论】:

    • 嗨!谢谢,但删除 'setCustomMessages' 行不会改变任何东西..
    • 我不明白打电话给setCustomMessages() 有什么问题。结果应该是一样的。
    • @Camilo 没问题,但为什么要做两次同样的事情?
    • 绝望的尝试.. :D
    • @TarasLonevsky 它没有回答这个问题。您可以将其添加为评论而不是答案。
    【解决方案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'),
     ];
    

    尽量不要使用 :255 和 :6 结尾。


    错误:

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

    正确:

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

    【讨论】:

    • 请为您的答案添加解释。仅代码的答案通常没有用,因为它们不教代码的作用,为什么应该使用它等。此外,这与 Indraanswer 有何不同?它看起来几乎像复制粘贴。
    猜你喜欢
    • 2018-12-17
    • 1970-01-01
    • 2014-05-31
    • 2017-06-28
    • 2017-12-13
    • 2011-08-09
    • 2020-07-18
    • 2020-10-18
    • 2011-09-29
    相关资源
    最近更新 更多