Check that the date is correct

1

I have to check that the date that a user enters is correct. It has to have the pattern dd / mm / yyyy.

What I can not do is check that the date is valid (02/30/2008) or (10/33/2018), for example.

 validDates() {
        let okey: boolean = true;

    try {
        // Se coge la fecha y se descompone con /
        const [d, m, y] = this.filterDateStart.split('/');
        // Sino encuentra las / fallará
        if (!d || !m || !y) {
            throw new Error();
        }
        // Sino eran números fallará
        if (isNaN(d) || isNaN(m) || isNaN(y)) {
            throw new Error();
        }
        // Sino cumple la longitud fallará
        if (d.length < 2 || m.length < 2 || y.length < 4) {
            throw new Error();
        }
        // finalmente creo el objeto date con los datos, resto 1 al mes.
        // 02 "Febrero" lo cogería como Marzo.
        let date: Date = new Date(y, m - 1, d);
    } catch (error) {
        okey = false;
    }
    return okey;
}

My intention is when a date that is not valid is created, the constructor of the Date class bursts, but it does not burst and it creates February 30 as if it were something ....

    
asked by EduBw 24.10.2018 в 16:55
source

1 answer

0

The easiest way to validate dates is to try to create them and check if the constructor tells you if it is an invalid date:

let stringFecha = "32/10/2018";
const [d, m, y] = stringFecha.split('/');
// cambiamos al estandar de fecha yyyy/mm/dd (de otra forma no te podrá convertir un string a fecha de forma apropiada)
const dateConversion = new Date('${y}/${m}/${d}');
console.log((dateConversion == "Invalid Date"));
    
answered by 24.10.2018 в 20:22