【问题标题】:Custom Laravel validation messages自定义 Laravel 验证消息
【发布时间】:2017-12-13 22:38:43
【问题描述】:

我正在尝试在 Laravel 5 中创建用于验证的自定义消息。这是我迄今为止尝试过的:

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

但它不起作用。该消息仍与默认消息相同。我该如何解决这个问题,以便我可以使用我的自定义消息?

【问题讨论】:

  • 这些年来,没有人指出这个简单的错字。在Validator::make() 内部,$messages 变量被意外放入了规则数组中。

标签: php laravel laravel-validation


【解决方案1】:

您可以提供自定义消息,例如:

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

您尝试过的方式,您错过了Validator::replacer(),以替换:variable

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

您可以从here 阅读更多内容,从here 阅读更多内容

【讨论】:

  • 任何示例如何使用它?
  • 第一种方法的添加示例。
【解决方案2】:

如果您使用$this->validate() 最简单的一种,那么您应该编写类似这样的代码..

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

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

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

【讨论】:

  • 我应该用什么填充 $request 变量?
【解决方案3】:

Laravel 5.7.*

你也可以尝试这样的事情。对我来说,当您想要验证请求时,在方法中制作自定义消息是最简单的方法:

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

【讨论】:

  • 这对我来说是最简单的,因为我时间紧迫,只需要在一个地方完成。它非常方便,但如果您需要在多个地方自定义消息,将它们全部放在一个地方会更谨慎。与在每个验证语句中都有自定义消息相比,它使跟踪更容易并使代码更清晰。由于我独特的用例,我赞成你的回答,我想说谢谢你(尽管 SO 建议不要感谢,我也发帖,你需要知道你帮助我摆脱了束缚并且我及时交付了)。
  • 非常感谢@Mexen 我很高兴能帮上忙!
  • @Geo4you 非常感谢,它真的帮助了我。
【解决方案4】:
$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

【讨论】:

【解决方案5】:

对于 Laravel 8.x7.x6.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'],

希望这会有所帮助...

【讨论】:

  • 这太棒了。我在文档中错过了这个。谢谢!
【解决方案6】:
//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.

【讨论】:

    【解决方案7】:

    你也可以使用setAttributeNames()setCustomMessages()的方法, 像这样:

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

    【讨论】:

    • 我真的很喜欢这种方法。与 FormRequest 上的后钩一起使用时非常棒,例如。 laravel.com/docs/8.x/…
    【解决方案8】:

    对于那些没有解决这个问题的人(在 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();
    }
    

    【讨论】:

      【解决方案9】:
          $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);
      

      【讨论】:

        【解决方案10】:

        运行以下命令在 Laravel 上创建自定义规则
        我假设名称是 CustomRule

        php artisan make:rule CustomRule
        
        

        结果,命令被创建,例如 PHP 代码

        如果规则中没有所需的关键字,则该规则将不起作用

        <?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.';
            }
        }
        
        
        

        并且是时候使用它了 首先,如果我们还没有,我们应该创建一个请求类

        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.',
                ];
            }
        }
        
        

        在您的控制器上,您应该向控制器注入自定义请求

        你的控制器方法

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

        【讨论】:

          猜你喜欢
          • 2014-05-31
          • 2017-06-28
          • 2020-07-18
          • 2016-01-29
          • 2015-07-13
          • 1970-01-01
          • 1970-01-01
          • 2017-11-19
          • 2019-11-01
          相关资源
          最近更新 更多