tom harrison
tom harrison

Reputation: 3433

incorrect date validation using moment

Im trying to use moment to validate the date input on my form, however for non existent dates such as 30th february instead of saying invalid date it will add the extra day onto the month meaning that it will output 1980-03-01 instead of taking the date as 1980-03-01 and invalidating the date

How can I get it to validate the date correctly?

const validateDate = (year, month, day) => {
    let validationMessage;
    const isNotEmpty = year && month && day;
    const date = isNotEmpty && `${year}-${month}-${day}`;
    const dateFormat = 'YYYY-MM-DD';
    const toDateFormat = moment(new Date(date)).format(dateFormat);
    const isDateValid = moment(toDateFormat, dateFormat, true).isValid();
    const isYearValid = (year > 1900 && year < new Date().getFullYear());

    if (!isDateValid) {
        validationMessage = `invalid date`;
    }

    return {
        isValid: isDateValid && isYearValid,
        validationMessage,
    };
};

export default {
    validate: validateDate
};

Upvotes: 1

Views: 183

Answers (1)

Michael Mishin
Michael Mishin

Reputation: 571

const date = moment('2020-02-30', 'YYYY-MM-DD', true);
const isValid = date.isValid(); //false

const date = moment('2020-02-28', 'YYYY-MM-DD', true);
const isValid = date.isValid(); //true

Upvotes: 2

Related Questions