Laravel 5.1 验证规则 alpha 不能占用空格

2022-08-30 16:46:26

我创建了一个注册表,农民将输入他的名字。名称可以包含连字符或空格。验证规则写入文件:app/http/requests/farmerRequest.php

public function rules()
{
    return [
        'name'     => 'required|alpha',
        'email'    => 'email|unique:users,email',
        'password' => 'required',
        'phone'    => 'required|numeric',
        'address'  => 'required|min:5',
    ];
}

但问题是,由于该规则,该字段不允许任何空格。该字段为 。namealphanamevarchar(255) collation utf8_unicode_ci

我该怎么办,以便用户可以输入带有空格的名称?


答案 1

您可以使用仅明确允许使用字母、连字符和空格的正则表达式规则

public function rules()
{
    return [
        'name'     => 'required|regex:/^[\pL\s\-]+$/u',
        'email'    => 'email|unique:users,email',
        'password' => 'required',
        'phone'    => 'required|numeric',
        'address'  => 'required|min:5',
    ];
}

答案 2

你可以为此创建自定义验证规则,因为这是一个非常常见的规则,你可能希望在应用的其他部分(或者可能在下一个项目)上使用。

在您的应用程序/提供商/应用程序服务提供程序上.php

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    //Add this custom validation rule.
    Validator::extend('alpha_spaces', function ($attribute, $value) {

        // This will only accept alpha and spaces. 
        // If you want to accept hyphens use: /^[\pL\s-]+$/u.
        return preg_match('/^[\pL\s]+$/u', $value); 

    });

}

resources/lang/en/validation 中定义自定义验证消息.php

return [

/*
|--------------------------------------------------------------------------
| Validation Language Lines
|--------------------------------------------------------------------------
|
| The following language lines contain the default error messages used by
| the validator class. Some of these rules have multiple versions such
| as the size rules. Feel free to tweak each of these messages here.
|
*/
// Custom Validation message.
'alpha_spaces'         => 'The :attribute may only contain letters and spaces.',

'accepted'             => 'The :attribute must be accepted.',
 ....

并像往常一样使用它

public function rules()
{
    return [
        'name'     => 'required|alpha_spaces',
        'email'    => 'email|unique:users,email',
        'password' => 'required',
        'phone'    => 'required|numeric',
        'address'  => 'required|min:5',
    ];
}

推荐