Skip to content

Instantly share code, notes, and snippets.

@yakserr
Created June 14, 2022 11:07
Show Gist options
  • Save yakserr/b661c6cd9ac8b3c5cb5a6c2257ec1fb9 to your computer and use it in GitHub Desktop.
Save yakserr/b661c6cd9ac8b3c5cb5a6c2257ec1fb9 to your computer and use it in GitHub Desktop.
Add Custom Validation in laravel that accept only alphabet and whitespace
<!-- 1 -->
<!-- add your costum validation in function boot -->
<!-- location file : app/Providers/AppServiceProvider.php -->
<!-- Don't forget to add : use Illuminate\Support\Facades\Validator -->
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//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);
});
}
<!-- 3 -->
<!-- use it as usual -->
public function rules()
{
return [
'name' => 'required|alpha_spaces',
];
}
<!-- direct at controller -->
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|alpha_spaces'
]);
}
<!-- 2 -->
<!-- Define your custom validation message -->
<!-- location file : 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.',
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment