MomentJS - Date Validation


MomentJS handles date validation in an easy way. You need not write lots of code to validate date. isValid() is the method available on moment which tells if the date is valid or not. MomentJS also provides many parsing flags which can be used to check for date validation.

Parsing Flags

MomentJS provides the following parsing flags in cases where the date given is considered as invalid −

overflow − This will occur when the month given is 13th, day is 367th in an year or 32nd in a month, 29th for Feb on a non-leap year etc. Overflow contains the index of the invalid unit to match towards invalidAt. Note that -1 means no overflow.

invalidMonth − It shows an invalid month name. It will give the invalid month string or null.

Empty − When an input is given which is not a date. It gives a Boolean.

nullInput − A null input, like moment(null);It returns a Boolean.

invalidFormat − When the format given is empty such as moment('2018-04-25', []). It gives Boolean back.

userInvalidated − A date created explicitly as invalid, such as moment.invalid(). It returns Boolean.

meridiem − Indicates the meridiem (AM/PM) parsed, if any. It returns string.

parsedDateParts − It returns an array of date parts parsed such as parsedDateParts[0] as year, parsedDateParts[1] as month and parsedDateParts[2] as day. If no parts are present, but meridiem has value, date is invalid. It returns an array.

Consider the following example to understand date validation −

var a = moment("2018-18-10T10:20:25");



The invalidAt gives the output as 1 , which points to the month as the month value is greater than 12 and it overflows. If there is an overflow, invalidAt will give the output as shown in the table given here −

0 years
1 months
2 days
3 hours
4 minutes
5 seconds
6 milliseconds

If there are multiple overflows in the date given, it will be an output for the first overflowed index.