I have created a a registration form where a farmer will input his name. The name may contain hyphen or white spaces. The validation rules are written in the app/http/requests/farmerRequest.php
file:
public function rules()
{
return [
'name' => 'required|alpha',
'email' => 'email|unique:users,email',
'password' => 'required',
'phone' => 'required|numeric',
'address' => 'required|min:5',
];
}
But the problem is the name
field is not allowing any white spaces because of the alpha
rule. The name
field is varchar(255) collation utf8_unicode_ci
.
What should I do, so that user can input his name with white spaces?
You can use a Regular Expression Rule that only allows letters, hyphens and spaces explicitly:
public function rules()
{
return [
'name' => 'required|regex:/^[\pL\s\-]+$/u',
'email' => 'email|unique:users,email',
'password' => 'required',
'phone' => 'required|numeric',
'address' => 'required|min:5',
];
}
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
/**
* 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);
});
}
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',
];
}
You can use This Regular Expression to validate your input request. But, you should carefully to write RegEx rules to implement.
Here, you can use this Regex to validate only alphabet & space are allowed.
public function rules()
{
return [
'name' => ['required', 'regex:/^[a-zA-Z\s]*$/']
];
}
I know, this answer may little bit changes with others. But, here is why I make some changes :
Don't get me wrong. I know, other answer is good. But I think it's better to validate everything as specific as we needed, so we can secure our app.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With