Home > front end >  Js check if date string is valid but returns valid even for incorrect dates
Js check if date string is valid but returns valid even for incorrect dates

Time:07-23

im checking if the string is a valid date or not and this is my if statement

if ((new Date(str).toString()) !== 'Invalid Date') {
        return moment.utc(str).local().format('DD/MM/YYYY')
   }

but when it gets the following inputs it accepts these as a date

DEV-50003
NATSD-10002
NATSD-10003
NATSD-10004

what's the problem here?

thanks in advance!

CodePudding user response:

Your comparison !== is comparing data types as well and that new Date(str).toString()) when given an invalid date returns a literal string while you are comparing it to a string. Easy fix here is to change the comparison to != or put double quotes ie: "Invalid Date" rather than 'Invalid Date'

CodePudding user response:

after a while, I found a solution.

I removed Date and used moment and its strict mode.

if (moment(str, moment.ISO_8601).isValid()) {
        return moment.utc(str).local().format('DD/MM/YYYY')
   }

this worked for me. hope this one will help someone else
Thanks.

  • Related