Table of Content
When shooting information for insertion into a database, or utilize in additional processing, then it is crucial that you control what the user may input. Otherwise, you may wind up with values from the database which don’t have any relation to fact.
It’s essential to validate the information given by the user using a form before you process it. Among different types of information identification, identification of date is just one.
In this tutorial we discussed the way to do JavaScript date validation
1. Dd/mm/yyyy or dd-mm-yyyy arrangement.
2. Mm/dd/yyyy or mm-dd-yyyy arrangement.
Afterward, we take every portion of the series supplied by the user (i.e., dd, mm and yyyy) and check if dd is a legitimate date, then mm is a valid month, or two yyyy is a legal season. We also have assessed the leap year variable for February.
How to validate a date input with JavaScript?
In this instance, the date fields will only accept input that matches the pattern ‘dd/mm/yyyy’ (this may just as readily altered into ‘yyyy-mm-dd’ or ‘mm/dd/yyyy’). The time area enables input with ‘hh:mm’ after an optional ‘am’ or ‘pm’. The fields may also be vacant.
<script type="text/javascript"> function checkForm(form) { // regular expression to match required date format re = /^\d{1,2}\/\d{1,2}\/\d{4}$/; if(form.startdate.value != '' && !form.startdate.value.match(re)) { alert("Invalid date format: " + form.startdate.value); form.startdate.focus(); return false; } // regular expression to match required time format re = /^\d{1,2}:\d{2}([ap]m)?$/; if(form.starttime.value != '' && !form.starttime.value.match(re)) { alert("Invalid time format: " + form.starttime.value); form.starttime.focus(); return false; } alert("All input fields have been validated!"); return true; } </script>
If the input does not match the regular expression then an error message is introduced, the routine stops the form from filing by returning a false value, and the focus will transfer into the appropriate form field.
If all tests pass, then a value of true is returned that empowers the form to fill.
The code always depends on your validation needs. This small example can serve as a start to use date and time validation in JavaScript in the right way.