0

How to validate if a field is a ISOString format?

It work when I use valid date such as const create = '2018-08-02T02:07:49.214Z' but it break the script when I use const create = 'b';

Example:

//const create = '2018-08-02T02:07:49.214Z';
const create = 'b';


const dateParsed = new Date(Date.parse(create))
if(dateParsed.toISOString() === create){
 console.log(dateParsed.getTime())
} else {
 console.log('invalid date')
}

I get an error RangeError: Invalid time value but expecting invalid date from console log.

I'll-Be-Back
  • 10,530
  • 37
  • 110
  • 213
  • You can always just use `try-catch` – VLAZ Aug 01 '19 at 20:06
  • 1
    @TylerRoper No, `new Date(Date.parse("b"))` is an `Invalid Date` (a _truthy_ object), not `null`. It can be checked with `isNaN(Number(new Date(Date.parse("b"))))`. – Sebastian Simon Aug 01 '19 at 20:09
  • 1
    @SebastianSimon Huh. If you click the *"Copy snippet to answer"* button underneath OP's code and add `console.log(dateParsed)`, [it logs `null`](https://i.imgur.com/sXyAY7E.png). I suppose that explains my confusion. Thanks for the correction! – Tyler Roper Aug 01 '19 at 20:12

2 Answers2

1

To achieve expected result, add below condition

!isNaN(dateParsed) && dateParsed.toISOString() === create

Issue:

console error is valid , as it throws error with toISOString() of invalid date

working code for reference

const create = 'b';
const dateParsed = new Date(Date.parse(create))

if(!isNaN(dateParsed) && dateParsed.toISOString() === create){
 console.log(dateParsed.getTime())
} else {
 console.log('invalid date')
}
Naga Sai A
  • 10,771
  • 1
  • 21
  • 40
0

new Date(Date.parse(create)) will return an Invalid Date, since Date.parse('b') returns NaN. I would point you towards this question: Detecting an "invalid date" Date instance in JavaScript, which provides a couple ways to checking if a date is valid or not.

At least in this example case, it doesn't seem like ISO format is strictly required, but you should be able to construct a regex to at least match the structure (there may be other requirements for a truly valid ISO datestring, I'm not sure off the top of my head).

Nathan Gingrich
  • 171
  • 1
  • 6