How to Simplify Date Validation With Web Applications

calendar

Using moment.js to simplify handling different date formats

While working with javascript’s built in date object is good for most basic operations such as, parsing, comparisons, modifying. There are advanced cases where it does not provide the functionality needed and writing work arounds manually can be time consuming. This is where the popular moment.js javascript library shines.

While working on a web application which is used in multiple time zones, it presented a need to deal with dates in different date formats. While in the United States we would use the “mm/dd/yyyy” format, other countries may use formats like “yyyy/mm/dd” or “dd/mm/yyyy”. Our application was setup to allow each individuals to set up date formats not just by browser setting, but rather with a manual profile setting that propagated throughout the application.

This caused trouble when needed to perform client-side javascript date validations. Users could be entering dates in different formats, and trying to parse this in standard javascript date format was not supported directly. As a result we needed to utilize moment.js to work with these variable date formats.

Without moment.js, you would create a date object from a string using the following:

New Date(date_string);

Using this directly, would result in some different results. For example if input is Jan 31 2007

New Data(“1/31/2007”); ok
New Data(“2007/1/31”); ok
New Data(“31/1/2007”); error

To get around this limitation we can use moment.js. When creating a momentjs object we can specify the date format as a string. In our app, we can supply this value based on each individual client international date format.

New moment(date_string, date_format_string);
New moment(“31/1/2007”, “DD/MM/YYYY”); ok

Once you have successfully created the momentjs object, you can perform all necessary date related functions.

moment(value,dateFormat).isValid(); – To check if date is entered in specified format

function CompareDates(date1, date2) {
var date1 = moment(date1, dateFormatJS);
var date2 = moment(date2, dateFormatJS);
if (date1.isBefore(date2)) {
return -1;
} else if (date1.isSame(date2)) {
return 0;
} else if (date1.isAfter(date2)) {
return 1;
}
}

This function can be used to compare date values

Using moment.js in our project has made working with dates much easier and saved us a lot of time by providing a good range of parsing and date manipulation tools.