Blog of Raivo Laanemets

Stories about web development, consulting and personal computers.

Date format validation with Moment.js

On 2014-11-03

Moment.js is a versatile date manipulation library for JavaScript. It supports parsing/validating/modifying/formatting operations. However, there is an important gotcha that could be missed when using the library. Its date parsing algorithm is very liberal and you might get bad surprises when using it:

> var moment = require('moment');
undefined
> moment('01.01.2001', 'DD.MM.YYYY').isValid()
true
> moment('01.01.2001junk text here', 'DD.MM.YYYY').isValid()
true
> moment('01.01.2abc', 'DD.MM.YYYY').isValid()
true
> moment('01', 'DD.MM.YYYY').isValid()
true
> moment('123', 'DD.MM.YYYY').isValid()
true
> moment('abc 123', 'DD.MM.YYYY').isValid()
true

This makes validation completely useless. The strict date parsing mode has to be enabled and it makes a lot of difference:

> moment('01.01.2001', 'DD.MM.YYYY', true).isValid()
true
> moment('01.01.2001junk text here', 'DD.MM.YYYY', true).isValid()
false
> moment('01.01.2abc', 'DD.MM.YYYY', true).isValid()
false
> moment('01', 'DD.MM.YYYY', true).isValid()
false
> moment('123', 'DD.MM.YYYY', true).isValid()
false
> moment('abc 123', 'DD.MM.YYYY', true).isValid()
false