This blog is about how to check if a string value in “yyyymmdd” format is valid date. The TypeScript code below is the function that I have created.
The function returns true only if the date exists on the calendar.
If you are reading this blog, you probably know that new Date(2021, 2, 29) returns 2021–3–1, not throwing an error or returning false even though 2021–2–29 does not exist on the calendar.
I made this function returns false when the date overflows the month. I tried to check the 5th and 6th characters such as “02” in the example of “20210229” matches with the month of new Date(2021, 2, 29), which is 3.
I have tested that the function with “20200229” or “20240229” returns true because the year of 2020 and 2024 do have 29th day in Feb. It means it works.
The function takes only string-formatted date such as “20190214”, “2019–02–14”. If the format does not conform, it returns false as well.
If you pass value like “20190229”, it also returns false because the year of 2019 does not have 29th day in Feb.
If you pass a silly day like 20191355, it also returns false.