【问题标题】:Laravel Form Request custom error message for regex ruleLaravel Form Request 正则表达式规则的自定义错误消息
【发布时间】:2019-04-17 00:59:35
【问题描述】:

我正在尝试在表单请求中为我的正则表达式显示自定义验证错误消息,到目前为止我还没有成功。

这是我的表单请求逻辑,正则表达式规则只接受字母和数字。

<?php

namespace App\Http\Requests\discounts;

use Illuminate\Foundation\Http\FormRequest;

class CheckoutCode extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'code' => 'required|string|min:7|max:7|regex:/([A-Za-z0-9 ])+/',
        ];
    }


    public function messages()
    {
        return [
            'code.regex' => 'Estas jodido'
        ];
    }


}

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    您可以使用现有的 Laravel 验证规则来实现这一点:Alpha num。来自文档:

    alpha_num

    正在验证的字段必须完全是字母数字字符。

    所以你的验证可以是这样的:

    // ...
    
    public function rules()
    {
        return [
            'code' => 'required|string|min:7|max:7|alpha_num',
        ];
    }
    
    // ...
    

    【讨论】:

      猜你喜欢
      • 2013-12-17
      • 2011-02-02
      • 2015-09-07
      • 2016-07-22
      • 2018-06-16
      • 2013-11-04
      • 2019-12-05
      • 2018-04-30
      • 1970-01-01
      相关资源
      最近更新 更多