In this article, I’ll discuss how to validate date format (yyyy/mm/dd) in Javascript.
If you are taking user input and you need to ensure that the user enters the date in valid format as we specified. You can validate the user input at the time of form submission or on onBlur event.
So let’s start
1 2 3 |
// User input, taking some random value for demostration var dateVal = "1981/02/31"; |
If the value is blank then return false
1 2 3 4 |
// In case if user doesn't enter anything if(dateVal == '') return false; |
We match the value in the format of yyyy/mm/dd, so let’s write some regex.
How to get current date time in Javascript
1 |
var validatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/; |
d{4} – Represents exactly four digit. We are checking this in case of year.
d{1,2} – Represents minimum digit in the range of 1 to 2. Month and Date can be either be single digit or multiple digit.
Check whether the enter value and format we specify match
1 |
var dateValues = dateVal.match(validatePattern); |
If it doesn’t match, it returns null
1 2 |
if (dateValues == null) return false; |
If the enter value is match with the pattern specified, it returns the array of matching value
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Now take year, month and date and put some additional validation dtYear = dateValues[1]; dtMonth = dateValues[3]; dtDay= dateValues[5]; // If month is less than 1 and greater than 12 then return false if (dtMonth < 1 || dtMonth > 12) return false; else if (dtDay < 1 || dtDay> 31) return false; else if ((dtMonth==4 || dtMonth==6 || dtMonth==9 || dtMonth==11) && dtDay ==31) return false; else if (dtMonth == 2) { var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0)); if (dtDay> 29 || (dtDay ==29 && !isleap)) return false; } |
Complete Javascript Code Validate Date Format (yyyy/mm/dd)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
function validateDateFormat(dateVal){ var dateVal = dateVal; if (dateVal == null) return false; var validatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/; dateValues = dateVal.match(validatePattern); if (dateValues == null) return false; var dtYear = dateValues[1]; dtMonth = dateValues[3]; dtDay= dateValues[5]; if (dtMonth < 1 || dtMonth > 12) return false; else if (dtDay < 1 || dtDay> 31) return false; else if ((dtMonth==4 || dtMonth==6 || dtMonth==9 || dtMonth==11) && dtDay ==31) return false; else if (dtMonth == 2){ var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0)); if (dtDay> 29 || (dtDay ==29 && !isleap)) return false; } return true; } |