Search code examples
phpformsvalidationlaravellaravel-5.1

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?


Solution

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