I have a little problem and i don't know how to fix it.
I have a select like this in my request
<select name="start_time" id="time">
<option>Aanvangstijd *</option>
<option value="11:00" id="time">11:00</option>
<option value="11:30" id="time">11:30</option>
<option value="12:00" id="time">12:00</option>
</select>
But the first option <option>Aanvangstijd *</option>
should not pass the validation in my request, but it of course does because it has a value.
Here is my Request
public function rules()
{
return [
'name' => 'required',
'phone' => 'required',
'email' => 'required',
'msg' => 'required',
'start_time' => 'required',
'avg' => 'required',
];
}
So my question is, how can I get it to work that it only passes this validation when an option is passed that isn'tAanvangstijd *`
CodePudding user response:
Laravel has great validation rules so you can be strict and specific about what is allowed in the input, including the date/time format. From what I see, you expect "start_time" input
- to be required
- to be string
- of 5 characters
- and to be valid time.
So, we can write just that:
public function rules()
{
return [
'name' => 'required',
'phone' => 'required',
'email' => 'required',
'msg' => 'required',
'start_time' => 'required|string|size:5|date_format:H:i',
'avg' => 'required',
];
}
Maybe you wish to limit the time range between 11:00 and 12:00, or, specifically:
- to be equal or after 11:00
- and to be equal or before 12:00
So you can add this rules on your validation:
'start_time' => 'required|string|size:5|date_format:H:i|after_or_equal:11:00|before_or_equal:12:00'
Additionaly you may wish to limit "start_time" to be only 11:00, 11:30 or 12:00:
'start_time' => 'required|string|size:5|date_format:H:i|after_or_equal:11:00|before_or_equal:12:00|in:11:00,11:30,12:00',
At the and we can increase our readability by using array syntax:
public
function rules()
{
return [
'name' => 'required',
'phone' => 'required',
'email' => 'required',
'msg' => 'required',
'start_time' => [
'required',
'string',
'size:5',
'date_format:H:i',
'after_or_equal:11:00',
'before_or_equal:12:00',
Rule::in(['11:00', '11:30', '12:00']),
],
'avg' => 'required',
];
}
And, one advice: TRUST NO ONE, NOT EVEN YOU! Even if you wrote frontend code and (you think) you are 100% sure you know what your html form will be sending your backend, please, use good, strict validation rules.