View Single Post
Old 12-08-2012, 07:53 AM   PM User | #6
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,033
Thanks: 197
Thanked 2,410 Times in 2,388 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
Code:
function validDate() {
var re= /^\d{2}[.\/-]\d{2[.\/-]\d{4}$/;
if (re.test(addDueDate)== false) {
	alert("please enter a valid date");
}
}

That checks if the format of the date is correct, (but note that USA and UK formats differ), but does not at all check whether the date is valid - not 56th February, or 26th of month 34, or year 9235. So not very useful.

Code:
<script type = "text/javascript">

function checkValidDate(yr,mmx,dd) {

if (yr <1910 || yr >2012) {  // you may want to change 2012 to some other year!
alert ("Year is out of range")
return false;
}

mm = mmx-1;  // remember that in Javascript date objects the months are 0-11
var nd = new Date(yr,mm,dd);

var ndmm = nd.getMonth();
if (ndmm != mm) {
alert (dd + "/" + mmx + "/" + yr  + " is an Invalid Date!");
return false; 
}
else {
alert (dd + "/" + mmx + "/" + yr  + " is a Valid Date");
}
}

// USAGE:
checkValidDate(2012,2,20)  // 20th February 2012  yyyy/mm/dd
checkValidDate(2012,2,31)  // 31st February 2012  yyyy/mm/dd

</script>
As felgall says, alerts are used only for debugging/demonstration.
__________________

All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.

Last edited by Philip M; 12-08-2012 at 07:59 AM..
Philip M is offline   Reply With Quote