Laravel 注册用户名不重复和格式验证

暂无标签

验证不重复(unique):

app/Http/Controllers/Auth/RegisterController.php

return Validator::make($data, [
    'name' => ['required', 'string', 'max:255', 'unique:users', 'letter_num'],
    'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
    'password' => ['required', 'string', 'min:8', 'confirmed'],
    'captcha' => ['required', 'captcha'],
], [
    'name.required' => '用户名必填',
    'name.unique' => '用户名已存在',
    'name.letter_num' => '用户名必须是字母或数字',
    'email.required' => '邮箱地址不能为空',
    'email.email' => '邮箱地址格式不正确',
    'email.unique' => '邮箱地址已被注册',
    'captcha.required' => '验证码不能为空',
    'captcha.captcha' => '请输入正确的验证码',
]);

验证格式:

alpha、alpha_num、alpha_dash无法验证中文。
所以自定义验证格式(letter_num),仅字母、数字和下划线:
app/Providers/AppServiceProvider.php
添加:

use Illuminate\Support\Facades\Validator;
public function boot()
{
    // 添加自定义验证规则,允许字母、数字和下划线
    Validator::extend('letter_num', function ($attribute, $value, $parameters, $validator) {
        return is_string($value) && preg_match('/^[A-Za-z0-9_]+$/u', $value);
    });
}