I have a form with some fields which I want to validate using Laravel's validate()
method.
public function postSomething(Request $req) {
...
$this->validate($req, [
'text_input' => 'required',
'select_input' => 'required'
]);
...
}
The issue is that if the form is submitted without selecting an option from the select input it is ignored in the request and Laravel doesn't validate it despite the fact that it is added to the ruleset with the required
validation rule. Empty text inputs are being validated correctly.
+request: ParameterBag {#42 ▼
#parameters: array:1 [▼
"text_input" => ""
"_token" => "TCDqEi2dHVQfmc9HdNf8ju1ofdUQS6MtDBpUMkl7"
]
}
As you can see, the select_input
is missing from request parameters if it was left empty.
Here is the HTML code for my select input:
<select class="form-control" name="select_input">
<option disabled selected>Please select...</option>
<option value="val1">Value 1</option>
<option value="val2">Value 2</option>
</select>
Is there a way to make the validation work for all fields from the ruleset even if some of them are not present in the request?
From Laravel 5.1 validation documentation:
required
The field under validation must be present in the input data and not empty. A field is considered "empty" is one of the following conditions are true: The value is null. The value is an empty string. The value is an empty array or empty Countable object. The value is an uploaded file with no path.
P.S. I'm using Laravel 5.1, so present
method is not available.
null
inputs are not included in the request body. It happens for radio inputs and checkboxes as well. – Esethvalue=""
to<option disabled selected>Please select...</option>
and Your rule should looks like'select_input' => 'required|in:val1,val2'
;) – Marabocpresent
validation method from Laravel 5.2 would work, but unfortunately I can't upgrade the project to a newer version because there are a lot of things I would need to change... – Eseth