Laravel 5.1 validation rule alpha cannot take whitespace - php

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 :
Using array in rules. As mention in Laravel Docs, you should better using array as rules when using Regex.
Using specified Regex for validate input request. Of course, you can selected answer above, but I recently found some bug with it. It allow Empty Characters to pass validation. I know, this might little bit paranoia, but if I found the better answer, why not using it?.
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.

Related

Laravel Validation rules: required_without

I have two fields: Email and Telephone
i want to create a validation where one of two fields are required and if one or both fields are set, it should be the correct Format.
I tried this, but it doesnt work, i need both though
public static array $createValidationRules = [
'email' => 'required_without:telephone|email:rfc',
'telephone' => 'required_without:email|numeric|regex:/^\d{5,15}$/',
];
It is correct that both fields produce the required_without error message if both are empty. This error message clearly says that the field must be filled if the other is not. You may change the message if needed:
$messages = [
'email.required_without' => 'foo',
'telephone.required_without' => 'bar',
];
However, you must add the nullable rule, so the format rules don't apply when the field is empty:
$rules = [
'email' => ['required_without:telephone', 'nullable', 'email:rfc'],
'telephone' => ['required_without:email', 'nullable', 'numeric', 'regex:/^\d{5,15}$/'],
];
Furthermore: It is recommended writing the rules as array, especially when using regex.

Is there a way to set a validation on multiple inputs with similar name? Laravel 5.6

Is there a way to set a validation on multiple inputs with similar name? For ex -
public function rules()
{
return [
'zone1' => 'required|numeric',
'zone2' => 'required|numeric',
'zone3' => 'required|numeric',
];
}
Can I do something like 'zone*' => 'required|numeric'
You can use an asterisk as a wildcard but it may not be a great idea. With a rule like 'zone*' => 'required|numeric' as long as there's a single value that matches the condition the request will pass validation. For example, if a request has a valid value for zone2 but zone1 and zone3 are missing or non-numeric the validation will still pass

Laravel validation rules - optional, but validated if present

I'm trying to create a user update validation through form, where I pass, for example 'password'=>NULL, or 'password'=>'newone';
I'm trying to make it validate ONLY if it's passed as not null, and nothing, not even 'sometimes' works :/
I'm trying to validate as :
Validator::make(
['test' => null],
['test' => 'sometimes|required|min:6']
)->validate();
But it fails to validate.
Perhaps you were looking for 'nullable'?
'test'=> 'nullable|min:6'
Though the question is a bit old, this is how you should do it. You dont need to struggle so hard, with so much code, on something this simple.
You need to have both nullable and sometimes on the validation rule, like:
$this->validate($request, [
'username' => 'required|unique:login',
'password' => 'sometimes|nullable|between:8,20'
]);
The above will validate only if the field has some value, and ignore if there is none, or if it passes null. This works well.
Do not pass 'required' on validator
Validate like below
$this->validate($request, [
'username' => 'required|unique:login',
'password' => 'between:8,20'
]);
The above validator will accept password only if they are present but should be between 8 and 20
This is what I did in my use case
case 'update':
$rules = [
'protocol_id' => 'required',
'name' => 'required|max:30|unique:tenant.trackers'.',name,' . $id,
'ip'=>'required',
'imei' => 'max:30|unique:tenant.trackers'.',imei,' . $id,
'simcard_no' => 'between:8,15|unique:tenant.trackers'.',simcard_no,' . $id,
'data_retention_period'=>'required|integer'
];
break;
Here the tracker may or may not have sim card number , if present it will be 8 to 15 characters wrong
Update
if you still want to pass hardcoded 'NULL' value then add the
following in validator
$str='NULL';
$rules = [
password => 'required|not_in:'.$str,
];
I think you are looking for filled.
https://laravel.com/docs/5.4/validation#rule-filled
The relevant validation rules are:
required
sometimes
nullable
All have their uses and they can be checked here:
https://laravel.com/docs/5.8/validation#rule-required
if you want validation to always apply
https://laravel.com/docs/5.8/validation#conditionally-adding-rules
if you want to apply validation rules sometimes
https://laravel.com/docs/5.8/validation#a-note-on-optional-fields
if you want your attribute to allow for null as value too

Laravel Request

I am trying to validate some form inputs using laravel request. The name may contain hyphen or dots (for example Mr. Example-of-name). The validation rule alpha cannot take any hyphen or dots. how to do this validation then? and also for the address, user may use comma between Road No, Sector No. etc. For phone number if I use exactly:11. it cannot take phone number with 11 digits. I get error message that the phone should be 11.
public function rules()
{
return [
'name' => 'required|max:60',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:4|confirmed',
'phone' => 'required|numeric',
'address' => 'required|min:5',
'profession' => 'required|min:3',
'conditions' => 'required'
];
}
Use Laravel's build-in regular expressions (regex) validation rule for this:
Regular Expressions for Requests

Laravel if field required, don't return error for each value?

I have a very large registration form.
'username_c' => 'required|unique:contacts_cstm',
'password' => 'required|min:6',
'email' => 'required|email',
'password_repeat' => 'required|same:password',
'first_name' => 'required',
'last_name' => 'required',
'rsa' => 'required',
And so on (another 15 fields)...
The problem is if the form is submitted with nothing entered, about 20 different errors are returned (as they should be).
Except, it would be nice if any of the required fields is NOT entered, to spit back one error saying "All fields are required" or something similar.
I've read through Laravel's docs. on this and didn't find anything. Is there any easy way to do this?
Assuming that all of your fields in the $rules array are required, you should be able to do something as simple as an array_filter($required_fields_input), compare the length against that of your $required_rules and redirect back with a single error message/alert.
See code example below. I tried to keep it simple/commented enough...
Not tested at all ... but theoretically! .... ;)
class YourController {
// ...
public function postFormData()
{
$rules = [
// ...
'first_name' => 'required',
'last_name' => 'required',
'rsa' => 'required'
// ...
];
// Assuming all fields in $rules are "required"
$required_fields = array_keys($rules);
$required_fields_input = Input::only($required_fields);
// Clean out all empty/null fields
$input_not_empty = array_filter($required_fields_input);
if (count($input_not_empty) < count($required_fields))
{
$fill_them_all_in_message = "Please fill in all required fields.";
return Redirect::back()->withMessage($fill_them_all_in_message);
}
/**
* All required fields present
* Continue as usual ..
* .. Validate/Respond/etc...
*/
}
//...
}
I think that pretty much covers your main concern of
a.) Avoiding 15 messages that say "XYZ field is required" ....
b.) Still allowing for the rest of the validation/processing to continue as usual.
Hope that helps!

Categories