Last active
June 24, 2021 14:44
-
-
Save elena-kolevska/8580401 to your computer and use it in GitHub Desktop.
Custom alphabetic validator that allows spaces
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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',); | |
*/ |
According to 5.2 docs, do this way.
- Make provider via Artican CLI
" php artisan make:provider YourServiceProvider " - Register it in config/app.php file to providers array,
" ........
App\Providers\RouteServiceProvider::class,
App\Providers\YourServiceProvider::class, " - 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
Well this didn't worked for me.
So i did this way.
Just Paste this method in Validator.php
public function validateAlphaSpaces($attribute, $value, $params)
{
return preg_match('/^[\pL\s]+$/u', $value);
}
And your message in Validation.php
/*
|--------------------------------------------------------------------------
| Custom Validation Attributes
|--------------------------------------------------------------------------
|
| The following language lines are used to swap attribute place-holders
| with something more reader friendly such as E-Mail Address instead
| of "email". This simply helps us make messages a little cleaner.
|
*/
"alpha_spaces" => "The :attribute may only contain letters and spaces.",
And Its all done :).
Now call it as usual
public function rules()
{
return [
'applicantName' => 'required|alpha_spaces',
];
}