Laravel Form Request custom error message for regex rule

时间:2019-04-17 00:59:35

标签: php laravel

I'm trying to display a custom validation error message for my regex inside Form Request, I haven't succeded so far.

This is my Form Request logic, regex rule only accepts letters and numbers.

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


}

1 个答案:

答案 0 :(得分:0)

您可以使用现有的Laravel验证规则:Alpha num来实现。从文档中:

  

alpha_num

     

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

因此您的验证可以是这样:

// ...

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

// ...