The builder of Date
does not accept any string in any format. In this case, the string 30062016
in fact it is not accepted. And call Date.parse
with the same string does not help, because so much parse
how much the constructor accepts the same formats.
See in the documentation the formats that are accepted. Any format other than what is there can or not working, depending on the implementation of each browser (see here an example where a specific format gives difference between browsers).
Anyway, one way to check whether the date is valid is to extract the snippets you need and convert them to numbers by passing them to the Date
:
function dataValida(s) {
let dia = parseInt(s.substring(6, 8));
let mes = parseInt(s.substring(8, 10)) - 1;
let ano = parseInt(s.substring(10));
if (isNaN(dia) || isNaN(mes) || isNaN(ano)) return false;
let d = new Date(ano, mes, dia);
return dia == d.getDate() && mes == d.getMonth() && ano == d.getFullYear();
}
[ '00260030062016', '00260032012019', '00260030xy2016'].forEach(s => {
console.log(`${s} válido? ${dataValida(s) ? 'sim' : 'não' }`);
});
I use parseInt
to convert each chunk to number. If any of them are not number, the function already returns false
, because it is not a date.
I had to subtract 1 of the month because in Javascript the months are indexed to zero (January is zero, February is 1, etc - see here for more details).
Then I create the date and check if the values of the day, month and year are the same that I got from the string. This may sound strange, but if you create a date on January 32nd, for example, the Date
adjusts to February 1. Then if the values returned by getters are different, you know some invalid value has been passed.