Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Custom alphabetic validator that allows spaces
<?php
/* app/validators.php */
Validator::extend('alpha_spaces', function($attribute, $value)
{
return preg_match('/^[\pL\s]+$/u', $value);
});
/*
* add the validators.php file in start/global.php: require app_path().'/validators.php'
* and use it as usual: $rules = array('name' => 'required|alpha_spaces',);
*/
@insidert
Copy link

insidert commented Mar 16, 2016

According to 5.2 docs, do this way.

  1. Make provider via Artican CLI
    " php artisan make:provider YourServiceProvider "
  2. Register it in config/app.php file to providers array,
    " ........
    App\Providers\RouteServiceProvider::class,
    App\Providers\YourServiceProvider::class, "
  3. Edit the code in App\YourServiceProvider.php
    <?php namespace App\Providers; use Validator; use Illuminate\Support\ServiceProvider; class YourServiceProvider extends ServiceProvider { public function boot() { Validator::extend('alpha_spaces', function($attribute, $value) { return preg_match('/^[\pL\s]+$/u', $value); }); } public function register() { // } }

4.Add custom message in language file : resources\lang\en\validaton.php
'alpha_num' => 'The :attribute may only contain letters and numbers.', 'alpha_spaces' => 'The :attribute may only contain letters and spaces.',

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment