当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《Laravel5.1验证规则alpha不能占用空格》经验,为你挑选了2个好方法。

我创建了一个登记表,农民将输入他的名字.名称可能包含连字符或空格.验证规则写在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',
    ];
}

但问题是name由于alpha规则,该字段不允许任何空格.这个name领域是varchar(255) collation utf8_unicode_ci.

我该怎么做,以便用户可以用空格输入他的名字?



1> Bogdan..:

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

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> Chris Landez..:

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

在您的app/Providers/AppServiceProvider.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',
    ];
}


并且不要忘了在app / Providers / AppServiceProvider.php顶部添加use use Illuminate \ Support \ Facades \ Validator;;)
推荐阅读
殉情放开那只小兔子
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有