The try catch block is required to handle cases where we have junk data in the middle of the date string (ex: 2015abc123) and any other invalid dates.

validating date javascript-84

The Validate a Date snippet demonstrates validating a date based on a date range that the user enters.

In this example, the user selects a date from a calendar and then specifies the start and end dates to validate the specified date against.

The objective of this technique is to notify the user when user input to a field that requires a specific, required format (e.g., date fields) is not submitted in that format.

If the required format is not used, an alert dialog describes the nature of the error in text.

Once the user dismisses the alert dialog, it may be helpful if the script positions the keyboard focus on the field where the error occurred, although some users may expect the focus to remain on the last control focused prior to the alert appearing.

Authors should exercise care to ensure that any movement of the focus will be expected.For example, consider the following cases: To handle the above cases, the input date string is converted to date first and then back to string.Then the new converted dates are compared with the original input.Java script date validation function in Detail In dates, both the single digit second and double digit second formats are perfectly valid, that is the reason why the input string is converted into two different date formats in the function.In Javascript, the str2date function behaves differently when compared to other tools or programming language string to date conversion functions.Sometimes we receive inconsistent data especially if the sources are log files.