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

问题描述 投票:19回答:3

我创建了一个注册表,农民将在其中输入他的名字。该名称可能包含连字符或空格。验证规则写在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

我应该怎么做,以便用户可以输入带有空格的姓名?

php forms validation laravel laravel-5.1
3个回答
41
投票

您可以使用仅允许字母,连字符和空格的Regular Expression Rule

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

34
投票

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

在您的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',
    ];
}

0
投票

您可以使用This Regular Expression验证您的输入请求。但是,您应该仔细编写要执行的RegEx规则。

在这里,您可以使用此正则表达式来验证只允许使用字母和空格。

public function rules()
{
    return [
        'name'     => ['required', 'regex:/^[a-zA-Z\s]*$/']
    ];
}

我知道,这个答案可能会与其他人有所改变。但是,这就是为什么我要进行一些更改的原因:

  • 在规则中使用数组。如Laravel Docs中所述,使用Regex时最好将数组用作规则。
  • 使用指定的正则表达式验证输入请求。当然,您可以在上面选择答案,但是我最近发现了一些错误。它允许Empty Characters通过验证。我知道,这可能有点paranoia,但是如果我找到了更好的答案,为什么不使用它呢?。

不要误会我的意思。我知道,其他答案很好。但是我认为最好根据需要验证所有内容,以便我们保护应用程序的安全。

© www.soinside.com 2019 - 2024. All rights reserved.