-1

I'm having trouble validating the following string which comes from the new Date() Object. "2020-10-06T14:23:43.964Z". In my case, I'll be expecting either this input format or a new Date(). I'm trying to write something to do this similar to

const isValidDate = (d: Date):boolean => {
 if (d instanceof Date || /* check if valid Date string here */) {
   return true
 }
 return false
}
LTFoReal
  • 377
  • 5
  • 20
  • 2
    Does this answer your question? [Detecting an "invalid date" Date instance in JavaScript](https://stackoverflow.com/questions/1353684/detecting-an-invalid-date-date-instance-in-javascript) – Fraction Oct 06 '20 at 14:37
  • it looks like that only works if I want to check if the date is an instaceof a Date object, doesn't cover the tougher part where I might just be getting a string which is the output of the Date object. – LTFoReal Oct 06 '20 at 15:27

2 Answers2

0

Maybe this can help you.

Date.prototype.isValid = function () { 
  // If the date object is invalid it 
  // will return 'NaN' on getTime()  
  // and NaN is never equal to itself. 
     return this.getTime() === this.getTime(); 
};
  • 1
    You can just use `Number.isNaN` to check for `NaN`, that is much more understandable. Also, do not modify built-in prototypes. – H.B. Oct 06 '20 at 14:38
  • yeah checking if it is an instance of Date is the easy part I think, the challenge has been to check if the input is a string, does it fit the format of what `new Date()` returns. I've looked at Date().parse() as well and that just returns a number even if the format is '2020-10-06', not very useful for me when I don't want these dates. – LTFoReal Oct 06 '20 at 15:11
0

Found the second half of my problem from this post which goes into more details javascript regex iso datetime

the function I came up with should check if the input is an instance of a Date object or a string that matches the output of the Date object.

function isValidDate (d) {
  if (d instanceof Date) {
    return true;
  }
  return /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/.test(d) ? true : false
}

const d1 = new Date(); // true
const d2 = '2020-10-05'; // false
const d3 = '2020-10-06T14:23:43.964Z'; // true

console.log(isValidDate(d1))
console.log(isValidDate(d2))
console.log(isValidDate(d3))
LTFoReal
  • 377
  • 5
  • 20