Peter
Peter

Reputation: 9143

Validating dates using moment.js

I've got a little issues getting my dates validated using moment.js. Moment.js has the isValid() function. However, this does not seem to work in the manner I would expect it to work.

Code

var startDate = moment($('.input-start').val()).format('YYYY-MM-DD');
var endDate = moment($('.input-end').val()).format('YYYY-MM-DD');

if (startDate.isValid() && endDate.isValid()) {
    // The script will never come here
    // Additionally it throws a TypeError saying isValid is unavailable for startDate
}

I think this illustrates my issue but if further details are required, please dont hesitate to ask.

Upvotes: 0

Views: 1625

Answers (2)

Rajesh
Rajesh

Reputation: 24955

As commented by @ssbb, you will have to do

moment(dateString, format).isValid()

But here is the catch, moment has 4 parameters in constructor,

moment(dateString, format, timeZone, strict)

Note: Default value of strict is false

Sample

var dateStr = "10/2/2016";

var format = "YYYY-MM-DD";
var date = moment(dateStr, format);
console.log(date.isValid(), date.format(format))

var date1 = moment(dateStr, format, undefined, true)
console.log(date1.isValid(), date1.format(format))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>

Upvotes: 2

Juan Ferreras
Juan Ferreras

Reputation: 2861

Format function returns a string so you cannot apply the isValid function on it anymore.

If you want to check if two dates are valid, as per a specific format, you can do the following:

var startDate = moment($('.input-start').val(), 'YYYY-MM-DD').isValid();
var endDate = moment($('.input-end').val(), 'YYYY-MM-DD').isValid();

if (startDate && endDate) {
    ...
}

For more information check out the official docs from MomentJS that have more information on the matter.

Upvotes: 0

Related Questions