【问题标题】:How to custom message validator with Laravel如何使用 Laravel 自定义消息验证器
【发布时间】:2021-11-14 15:25:05
【问题描述】:

我正在制作一个 API,允许用户输入一些信息,如电子邮件、电话号码、地址...... 但是如果用户输入错误的电话号码,验证错误是

{
  "message": "The given data was invalid.",
  "errors": {
    "phone": [
      "The phone has already been taken."
    ]
  }
}

如你所见,返回的消息是

"message": "The given data was invalid."

。但我期待的消息是The phone has already been taken。如何按预期自定义消息?使用电子邮件验证器,消息是相同的,但密钥是 email。我期望的消息是

"message": "The ... has already been taken. "

我正在使用 laravel 8 并在请求中验证 示例函数rules()

    public function rules()
    {
        return [
            'profile_img' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:' . config('filesystems.max_upload_size'),
            'name' => 'nullable|min:3',
            'phone' => [
                'required',
                'numeric',
                new UpdatePhoneRule(User::TYPE_CLIENT),
            ],
            'email' => [
                'nullable',
                'email',
                new UpdateEmailRule(User::TYPE_CLIENT),
            ]
        ];
    }

谢谢

【问题讨论】:

    标签: laravel validation


    【解决方案1】:

    在请求 php 文件中,您可以使用此函数 failedValidation() 并传入验证器。这样,您可以在验证失败时更改或自定义响应。

    use Illuminate\Http\Exceptions\HttpResponseException;
    use Illuminate\Contracts\Validation\Validator;
    
        protected function failedValidation(Validator $validator) {
            throw new HttpResponseException(response()->json(['status'=>'failed',
                                                        'message'=>'unprocessable entity',
                                                        'errors'=>$validator->errors()->all()], 422));
        }
    

    示例响应在这里..

    {
    "status": "failed",
    "message": "unprocessable entity",
    "errors": [
        "The name must be a string.",
        "One or more users is required"
     ]
    }
    

    如您所见,消息已更改,您可以对响应消息执行任何操作。

    你也可以试试这个

    $validator->errors()->messages()[keyname]
    

    【讨论】:

    • 谢谢,成功了。
    【解决方案2】:

    您可以在 lang 文件中执行此操作:resources/lang/en/validation.php。例如,如果您只想更改整个应用程序中电子邮件字段上唯一规则的消息,您可以这样做:

    /*
    |--------------------------------------------------------------------------
    | Custom Validation Language Lines
    |--------------------------------------------------------------------------
    |
    | Here you may specify custom validation messages for attributes using the
    | convention "attribute.rule" to name the lines. This makes it quick to
    | specify a specific custom language line for a given attribute rule.
    |
    */
    
    'custom' => [
        'attribute-name' => [
            'rule-name' => 'custom-message',
        ],
        'email' => [
            'unique' => 'This email is already registered...etc',
        ]
    ],
    

    【讨论】:

      【解决方案3】:

      您必须在验证中使用unique

      $this->validate(
          $request, 
          [   
              'email'             => 'required|unique:your_model_names',
              'phone'             => 'required|unique:your_model_names'
          ],
          [   
              'email.required'    => 'Please Provide Your Email Address For Better Communication, Thank You.',
              'email.unique'      => 'Sorry, This Email Address Is Already Used By Another User. Please Try With Different One, Thank You.',
              'phone.required' => 'Your custom message',
              'phone.unique'      => 'The phone has already been taken'
          ]
      );
      

      【讨论】:

      • 谢谢,但这不是我期望的结果。非常感谢
      猜你喜欢
      • 2020-10-18
      • 2014-05-31
      • 2017-06-28
      • 2017-12-13
      • 2020-07-18
      • 2013-09-03
      • 1970-01-01
      • 2019-02-11
      • 2016-01-29
      相关资源
      最近更新 更多