Regular Expression for a date

I have this expression:

/(19|20)\d\d/)- /.- /.

to detect if my date:


is valid. It’s not working. What do I have wrong?

derfleurer, your expression still didn’t work for some reason. I’m using some old dreamweaver extension for form validation. I think I’ll rewrite that to use jquery’s validation. I might also just impliment mrhoo’s example as well. Choices, choices. Thank you all though.

odd. must be the script. Like I said, it’s old.

Tested on

1913 12 15

etc. works fine.

Awesome tool for working with regular expressions:

Regular Expression Analyzer

You have some unescaped characters and a few missing parentheses. You also have your days/months mixed.

/(19|20)\d{2}([\-\/ .])(0[1-9]|1[012])\2([012][0-9]|3[01])/

April 31 and February 29, 2010 are not ‘real’ dates,
but it takes a monster of a regular expression to catch them.

It might be more sensible to try to make a date from the input,
and check what you get.

function isValidYmd(s){
	s= s.split(/\\D+/);
	var y= +s[0], m= parseInt(s[1], 10)-1,
	d= parseInt(s[2], 10), day;
	  day= new Date(y, m, d);
	  return day.getMonth()== m && day.getDate()== d;
		return false;

alert(isValidYmd(‘2010-04-31’)); // false
alert(isValidYmd(‘2010-03-31’)); // true