I have created a a registration form where a farmer will input his name. The name may contain hyphen or white spaces. The validation rules are written in the app/http/requests/farmerRequest.php file:

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

But the problem is the name field is not allowing any white spaces because of the alpha rule. The name field is varchar(255) collation utf8_unicode_ci.

What should I do, so that user can input his name with white spaces?

推荐答案

You can use a Regular Expression Rule that only allows letters, hyphens and spaces explicitly:

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

Laravel相关问答推荐

在Laravel Livewire中,如果一个输入基于另一个唯一的字段是唯一的,如何判断验证?

如何在控制器中获取所需参数?

Inertiajs - 使用链接组件添加记录但无法在不使用表单的情况下清除文本区域

使用枢轴插入多对多时的Laravel问题

使用 App::environment() 与 app()->environment() 与 config('app.env') 之间的区别

FileViewFinder.php 第 137 行中的 Laravel 5 InvalidArgumentException:未找到视图 [.admin]

Laravel 控制器中一种特定方法的中间件

Laravel 4:验证前修剪输入的最佳实践

Laravel Request::input 调用未定义的方法

如何在中间件 Laravel 中获取请求的控制器和操作的名称

laravel Blade中多选选项中的旧值

在 AWS 上找不到 Laravel 5 类Collective\Html\HtmlServiceProvider

如何运行artisan命令计划:在托管服务器上运行? (Laravel )

如果用户未登录 Laravel,则重定向到登录

如何在 laravel 4 中删除文件

Laravel 如何具体构建和判断 CSRF 令牌?

Laravel 表:只能有一个自动列,并且必须定义为键

如何判断是否在laravel中使用了分页

在laravel中删除确认

以编程方式而不是从 CLI 运行 Laravel 5 seeder