Laravel Validator For Alphabetic Characters And Spaces

Custom validation rule for strings that might include spaces

Jan 23, 2014 1 min read

Note: (Written for Laravel version 4)

This is just a short one.. Have you ever received an error back from your name validators, when you type in a name like “Ana Maria”? Laravel doesn’t have a built in validator for alphabetic characters and spaces, but it does give us everything we need to build one.

This is how I do it:

/*
* app/validators.php
*/

Validator::extend('alpha_spaces', function($attribute, $value)
{
    return preg_match('/^[\pL\s]+$/u', $value);
});

It matches unicode characters, so poor João Gabriel won’t have his name marked as invalid anymore :)

Define your custom validation message in lang/xx/validation.php:

/*
|--------------------------------------------------------------------------
| Custom Validation Rules
|--------------------------------------------------------------------------
|
| Custom rules created in app/validators.php
|
*/
"alpha_spaces"     => "The :attribute may only contain letters and spaces.",

Use it as usual:

$rules = array(
    'name' => 'required|alpha_spaces',
    );

And don’t forget to require the validators.php file in start/global.php somewhere at the end:

require app_path().'/validators.php';

Here’s the gist, feel free to make it better.

comments powered by Disqus