Laravel require at least one field - validation

I'm building a form . there is 3 specific text filed that at least one of them should be filled by the user. how may i implement it with Laravel validation rules?
//dd($request)
array:6 [▼
"_token" => "o5td5RMv2EQ5mA7LqXpyMXCKIu7L78BfrRSEU1se"
"skill_id" => "6"
"plan_id" => "1"
//at least one of below fields should be filled
"context" => ""
"link" => ""
"desired_date" => ""
]

You can use:
required_without_all:foo,bar,...
In this the field under validation must be present only when all of the other specified fields are not present.
$rules = array(
'skill_id' => 'required_without_all:plan_id,context,link',
'plan_id' => 'required_without_all:skill_id,context,link',
);
OR
You can use the required_unless rule: https://laravel.com/docs/5.2/validation#rule-required-unless
required_unless:anotherfield,value,...
IN this case, the field under validation must be present unless the anotherfield field is equal to any value.

You can use required_without_all
$rules = array(
'context' => 'required_without_all:link,desired_date',
'link' => 'required_without_all:context,desired_date',
'desired_date' => 'required_without_all:context,link',
);

Related

Laravel - request validation for two nullable fields requiring at least one of them to be not-null

My model has two nullable fields, but at least one of them must be not-null.
How do I setup request validation for this ?
$request->validate([
'field_1' => ['nullable'],
'field_2' => ['nullable'],
...
]);
thanks
If you have only two filed comparisons then you can use required_without:foo,bar,...
$request->validate([
'field_1' => 'required_without:field_2',
'field_2' => 'required_without:field_1'
]);
if it has more than two fields then required_without_all:foo,bar,...
$request->validate([
'field_1' => 'required_without_all:field_2,field_3',
'field_2' => 'required_without_all:field_1,field_3',
'field_3' => 'required_without_all:field_1,field_2',
]);
As per Doc
required_without:foo,bar,...
The field under validation must be present and not empty only when any
of the other specified fields are empty or not present.
required_without_all:foo,bar,...
The field under validation must be present and not empty only when all
of the other specified fields are empty or not present.
Validation

Form not submitting even after I have removed "required" field - Laravel

I have about 8 fields (4 required and 4 optional) in my form and I have tested every field with "required" and other forms of validation rules.
Now I have removed the "required" rule in the optional ones but when I submit the form, the optional fields won't let me, the error I get on each is "The field is invalid".
Can someone please tell what needs to be done? All I want is 4 to be required and other 4 to be optional. Also, I did place other validation rules in the optional ones like "min, max and regex".
`$this->validate($request,[
'firstname' => 'required|regex:/^[a-zA-Z ]*$/|min:2|max:255',
'lastname' => 'regex:/^[a-zA-Z ]*$/|min:2|max:255',
'email' => 'required|email|max:255|unique:clients',
'telephone' => 'regex:^\+?([0-9]{2})-?([0-9]{3})-?([0-9]{6,7})*$^',
'job_title' => 'required|regex:/^[a-zA-Z. ]*$/|min:7|max:255',
'nationality' => 'regex:/^[a-zA-Z ]*$/|min:4|max:255',
'dob' => 'required|regex:/^[a-zA-Z0-9,. ]*$/|max:255',
'interests' => 'regex:/^[a-zA-Z,. ]*$/|min:10|max:255',
]);
`
As you can see, the ones not having required field are the ones not letting me submit the form.

Validate a single variable or an array in Laravel

I want to validate a single variable like this $name = "example name" but I didn't a way to handle it then I decided to convert it to an array like this $nameArr = ['name' => 'example name'];, the validator is
$rules =
$this->validate($nameArr, [
'name' => 'required|max:10|regex:/^[a-zA-Z0-9]+$/u',
], [
'name.required' => 'name is empty',
'name.max' => 'name must be more less than 10 letters',
'name.regex' => 'invalid name'
]
);
but the Laravel gives this error
Argument 1 passed to App\Http\Controllers\Controller::validate() must be an instance of Illuminate\Http\Request, string given
Correct, the validate function on Controller comes from Illuminate\Foundation\Validation\ValidatesRequests and requires the first paramter to be a request object.
If you want to validate an array, you will have to create the validator manually.
$validator = Validator::make($nameArr,
[
'name' => 'required|max:10|regex:/^[a-zA-Z0-9]+$/u',
],
[
'name.required' => 'name is empty',
'name.max' => 'name must be more less than 10 letters',
'name.regex' => 'invalid name'
]
);
if ($validator->fails()) {
dd($validator->errors());
}
After knowing that the parameter is passed as route url param, I would like to add another option which Laravel provides to validate :
Route::get('user/{name}', 'UserProfileController#getByName')
->where([ 'name' => '[a-z]{10,}' ]);
The where method validates the route param based on provided regular expressions. So [a-z]{10,} will make sure the name is present with 10 or more characters.
See documentation for more

Handling CodeIgniter form validation (rule keys and data types)

Okay, so I've been searching for a while this question, but couldn't find an answer (or at least some direct one) that explains this to me.
I've been using CodeIgniter 3.x Form Validation library, so I have some data like this:
// Just example data
$input_data = [
'id' => 1,
'logged_in' => TRUE,
'username' => 'alejandroivan'
];
Then, when I want to validate it, I use:
$this->form_validation->set_data($input_data);
$this->form_validation->set_rules([
[
'field' => 'id',
'label' => 'The ID to work on',
'rules' => 'required|min_length[1]|is_natural_no_zero'
],
[
'field' => 'username',
'label' => 'The username',
'rules' => 'required|min_length[1]|alpha_numeric|strtolower'
],
[
'field' => 'logged_in',
'label' => 'The login status of the user',
'rules' => 'required|in_list[0,1]'
]
]);
if ( $this->form_validation->run() === FALSE ) { /* failed */ }
So I have some questions here:
Is the label key really necessary? I'm not using the Form Validation auto-generated error messages in any way, I just want to know if the data passed validation or not. Will something else fail if I just omit it? As this will be a JSON API, I don't really want to print the description of the field, just a static error that I have already defined.
In the username field of my example, will the required rule check length? In other words, is min_length optional in this case? The same question for alpha_numeric... is the empty string considered alpha numeric?
In the logged_in field (which is boolean), how do I check for TRUE or FALSE? Would in_list[0,1] be sufficient? Should I include required too? Is there something like is_boolean?
Thank you in advance.
The "label" key is necessary, but it can be empty.
The "required" rule does not check length, nor does the "alpha_numeric". It checks that a value is present, it does not check the length of said value. For that, there is min_length[] and max_length[].
If you're only passing a 0 or 1, then this is probably the easiest and shortest route.

How to allow empty value for Laravel numeric validation

How to set not require numeric validation for Laravel5.2? I just used this Code but when i don't send value or select box haven't selected item I have error the val field most be numeric... I need if request hasn't bed input leave bed alone. leave bed validate ...
$this->validate($request, [
'provinces_id' => 'required|numeric',
'type' => 'required',
'bed' => 'numeric',
]);
If I understood you correctly, you're looking for sometimes rule:
'bed' => 'sometimes|numeric',
In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule to your rule list
In Laravel 6 or 5.8, you should use nullable. But sometimes keyword doesn't work on that versions.
Use sometimes instead of required in validation rules. It checks if only there is a value. Otherwise it treats parameter as optional.
You may need nullable – sometimes and
present didn't work for me when combined with integer|min:0 on a standard text input type - the integer error was always triggered.
A Note on Optional Fields
By default, Laravel includes the TrimStrings and ConvertEmptyStringsToNull middleware in your application's global middleware stack. These middleware are listed in the stack by the App\Http\Kernel class. Because of this, you will often need to mark your "optional" request fields as nullable if you do not want the validator to consider null values as invalid.
Tested with Laravel 6.0-dev
Full list of available rules
In laravel 5.5 or versions after it, we begin to use nullable instead of sometimes.
according to laravel documentation 8 you must to set nullable rule
for example:
$validated = $request->validate([
'firstName' => ['required','max:255'],
'lastName' => ['required','max:255'],
'branches' => ['required'],
'services' => ['required' , 'json'],
'contract' => ['required' , 'max:255'],
'FixSalary' => ['nullable','numeric' , 'max:90000000'],
'Percent' => ['nullable','numeric' , 'max:100'],
]);
in your case :
$this->validate($request, [
'provinces_id' => 'required|numeric',
'type' => 'required',
'bed' => 'nullable|numeric',
]);

Resources