laravel 5.5 修改注册表单验证规则

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了laravel 5.5 修改注册表单验证规则相关的知识,希望对你有一定的参考价值。

在这里我尝试了两种方法(新增验证类 和直接更改规则)修改验证规则

1.1  新增一个验证手机号码类,输入 php  artisan make:rule CheckMobile  然后修改该类

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class Checkmobile 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 preg_match(‘/^1[34578][0-9]{9}$/‘, $value); 
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return ‘请填写正确的手机号码!‘;
    }
}

1.2 在注册控制器中引用

 use App\Rules\Checkmobile;     
  ...

  protected function validator(array $data)
  {

    return Validator::make($data, [

‘name‘ => ‘required|string|max:8‘,
            ‘email‘ => ‘required|string|email|max:255|unique:users‘,
            ‘password‘ => ‘required|string|min:6|confirmed‘,
            ‘college‘ => ‘required|string|max:20‘,
            ‘class‘ => ‘required|string|max:20‘,
            ‘phone‘=> [‘required|mobile‘, new Checkmobile]
        ],
.....

 2.1 使用 Validator::extend() 直接修改

    protected function validator(array $data)
    {
        Validator::extend(‘mobile‘, function($attribute, $value, $parameters)
        {
            return preg_match(‘/^1[34578][0-9]{9}$/‘, $value);
        });

        return Validator::make($data, [
            ‘name‘ => ‘required|string|max:8‘,
            ‘email‘ => ‘required|string|email|max:255|unique:users‘,
            ‘password‘ => ‘required|string|min:6|confirmed‘,
            ‘college‘ => ‘required|string|max:20‘,
            ‘class‘ => ‘required|string|max:20‘,
            ‘phone‘=> ‘required|mobile‘,
        ],
        [   "min" => ":attribute 至少为 :min 位",
            "confirmed" => "两次输入 :attribute 不一致!",
            "required" => ":attribute 不能为空!",
            "mobile" => ":attribute 格式不正确!"
        ],
        [   "name" => "昵称",
            "password" => "密码",
            "phone" => "手机号码",
            "college" => "院校",
            "class" => "班级"
        ]);

顺带一提,这里虽然用 

Validator::make() 将字段指定为中文, 我还是引入了中文包

 




以上是关于laravel 5.5 修改注册表单验证规则的主要内容,如果未能解决你的问题,请参考以下文章

Laravel 5.5 / 验证器 / 自定义规则

Laravel 5.5 的自定义验证对象/类

Laravel 5.5 无法在表单请求类中制作验证器

Laravel 5.5 - 同时验证多个表单请求

Laravel 5.5 FormRequest 自定义表单请求验证类

Laravel 验证登录表单验证在密码确认中失败?