Link to home
Start Free TrialLog in
Avatar of hankknight
hankknightFlag for Canada

asked on

JavaScript: Validate Correct Date/Time Format

Using JavaScript, I want to test if a date and time is in the allowed format.

These values are valid:
2011-9-9 22:3:00
2001-11-11 0:23:55
2091-1-1 2:00:11


These values are NOT valid:
11-9-9 22:3:00
2001-11-11
2091-1-1 2:00:11 xyz

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Demo</title>
</head>
<body>

<input type="text" id="timeDate" />
<input type="button" value="test" onclick="checkTimeDateFormat(document.getElementById('timeDate').value)" />

<script type="text/javascript">
/*<![CDATA[*/

function checkTimeDateFormat(str) {
 alert('The Format of the Date/Time field is correct.');
 alert('The Format of the Date/Time field is NOT correct.');
}

/*]]>*/
</script>

</body>
</html>

Open in new window

SOLUTION
Avatar of Gurvinder Pal Singh
Gurvinder Pal Singh
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Just for the record, the solution I posted does utilize the regex pattern of \d{4,4}, which means that the minimum amount of digits is 4 and the maximum is 4, so it has to exactly be 4.
Forgot to add in my above comment that I am talking about the year input.  But going off what hankknight posted of valid and invalid dates, my pattern is explained as follows:

^\\d{4,4}-\\d{1,2}-\\d{1,2}\\s\\d{1,2}:\\d{1,2}:\\d{2,2}$

Open in new window


\\d{4,4} means 4 (and only 4) digits

\\d{1,2} means 1 or 2 digits

\\d{2,2} means 2 (and only 2) digits

My original solution works great tested with the valid/invalid date time entries hankknight supplied, in that one simple JavaScript function.

Thanks for the assist, and the points.

Good luck & have a great day.
Glad I could help ;)