I have a HTML form taking date and time as inputs:
<div>
<label for="date_of_appointment">Date of appointment *</label>
<input type="date" name="date_of_appointment" id="date_of_appointment"
value="<?php echo $date_of_appointment; ?>"
required oninvalid="setCustomValidity('Fill in the date')"
oninput="setCustomValidity('')">
</div>
<div>
<label for="time_of_appointment">Time of appointment *</label>
<input type="time" name="time_of_appointment" id="time_of_appointment"
value="<?php echo $time_of_appointment; ?>"
required oninvalid="setCustomValidity('Fill in the time')"
oninput="setCustomValidity('')">
</div>
I'm using the HTML5 input types date
and time
.
It's important to catch all the errors in all the browsers.
How would you design the validation for this to be sure the user will provide
the date and time in the correct format for inserting into the DB?
In my solution I would validate it as follows:
Not all browsers offer the time/date pickers. What is the expected format in those fields?
Let's say the expected date format is YYYY-MM-DD. I would split it with PHP explode() function and validate with PHP checkdate($month, $day, $year) function. And similarly created a routine for expected time format. Can I do more between step 1 and 2 with javascript, without the need to reload a page to tell the user that the format is wrong immediately he types something breaking the format?
- insert the values with correct format into DB.