Laravel validator for alphabetic characters and spaces
Elena Kolevska has a short tip for creating a custom Laravel validator.
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';
Link:
This post is submitted by our members. Submit a new post.
Tags: v4.x v4.1 v4.2 Tutorials Tips Intermediate Laravel 5 Laravel 5.1 Laravel 5.2