Last active
December 5, 2018 01:16
-
-
Save abdullahbutt/ea171f53e4af167d50d92d439c4d97d3 to your computer and use it in GitHub Desktop.
laravel alpha space validation rule
This file contains 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
In Laravel 5.4, I used the following way to define a alpha_spaces rule: | |
You can create a custom validation rule for this since this is a | |
pretty common rule that you might want to use on other part of your app | |
(or maybe on your next project). | |
-------------------------------------------------------------------------------------------- | |
on your app/Providers/AppServiceProvider.php | |
// Add below validator Namespace on top of file: | |
use Illuminate\Support\Facades\Validator; | |
/** | |
* Bootstrap any application services. | |
* | |
* @return void | |
*/ | |
public function boot() | |
{ | |
// If you are running lower version of MySQL then you may get following error : 1071 Specified key was too long; max key length is 767 bytes | |
// To fix this, I'm setting max string length of all db fields by default to 191 | |
Schema::defaultStringLength(191); //Solved by decreasing StringLength to 191 instead of by default 255 | |
//Add this custom validation rule. | |
Validator::extend('alpha_spaces', function ($attribute, $value) { | |
// This will only accept alpha and spaces. | |
// If you want to accept hyphens use: /^[\pL\s-]+$/u. | |
return preg_match('/^[\pL\s]+$/u', $value); | |
}); | |
} | |
Define your custom validation message in resources/lang/en/validation.php | |
return [ | |
/* | |
|-------------------------------------------------------------------------- | |
| Validation Language Lines | |
|-------------------------------------------------------------------------- | |
| | |
| The following language lines contain the default error messages used by | |
| the validator class. Some of these rules have multiple versions such | |
| as the size rules. Feel free to tweak each of these messages here. | |
| | |
*/ | |
// Custom Validation message. | |
'alpha_spaces' => 'The :attribute may only contain letters and spaces.', | |
'accepted' => 'The :attribute must be accepted.', | |
.... | |
and use it as usual | |
public function rules() | |
{ | |
return [ | |
'name' => 'required|alpha_spaces', | |
'email' => 'email|unique:users,email', | |
'password' => 'required', | |
'phone' => 'required|numeric', | |
'address' => 'required|min:5', | |
]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
On top app/Providers/AppServiceProvider.php
Add
use Illuminate\Support\Facades\Schema;