Date Validation in Javascript. Example using split and Regex for dd/mm/yyyy, mm/dd/yyyy format

There are many ways to check whether the input date is valid or not using Javascript. Let me explain the two ways. You can use any one of the ways which one you feel comfortable.

                For validating the date, first part will ensure the given date is in right format (dd/mm/yyyy or mm/dd/yyyy) that means, the given date string should have two slashes only and the remaing characters should be a digit(numeric). Next part will ensure the digits (day, month, year) should be in valid range which means days should be in the range 1 to 31 (February- 28 days, for leap year 29 days), month should be in the range 1 to 12. In our example, isValidDate() function will accept date either in dd/mm/yyyy format or mm/dd/yyyy format. Change the logic accordingly as given below. In the first method, we are splitting the dd, mm, yyyy using substring method. isDigit () funtion is used to validate the dd, mm, yyyy is numeric or not and we have written logic to check the day, month, year is in the valid range.

             In the Second method, Date is split using Regular expression. After splitting the date, new Date(yyyy, mm-1, dd) is used to form date. Now getDate(date), getMonth(date), getYear(date) is used to check the day, month or year is valid by comparing dd with the result of getDate(date), mm with the result of getMonth(date) and yyyy with the result of getYear(date). If day, month, year is valid means, the date is also valid.

Leave a Reply