Noob Coder Noob Coder - 4 months ago 21
PHP Question

Laravel 5.1 validation rule alpha cannot take whitespace

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?

Answer

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',
    ];
}
Comments