Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript function to check if string is a valid date

I know this has been asked several times, but I am asking because after scouring the internet for several hours, I have not found a viable solution that does not include using a Javascript library.

I am simply looking for a way to test whether or not a string is a valid date. I am binding data in Javascript passed from C# (JSON.NET). The format of a valid datetime that is being passed back is '2083-01-01T00:00:00'. All of the functions I have found either say this is invalid, because they are not including the timestamp portion as allowable, or they are not strict enough, and say that this string, 'Testing 21215', is a valid date.

What is a solution that I could use to validate this format, without using a library?

like image 273
user2023116 Avatar asked Apr 10 '26 16:04

user2023116


1 Answers

If you are guaranteeing that the format will always be in that ISO standard format, then you can use a regular expression to test the structure as a string. You can get crazy detailed with this if you want, or try the following.

var dateRegexp = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/
var matches = dateString.match(dateRegexp)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match

There might be other drastically different approaches as well. My preferred way is to try and use the new Date(string) method; if this parses correctly, then you can convert it back to the ISO string

var dateString = "2016-03-18T00:00:00";
var date = new Date(dateString);
console.log(date.toISOString());

However, you might need to be aware of the implications of this for international users.

like image 91
Jim Pedid Avatar answered Apr 13 '26 06:04

Jim Pedid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!