Thursday, February 16, 2006

How to Check for Date Format using Javascript

One Small Example of how to validate a Input box content against a given mask using Javascript. For this example I have picked up "date" as our input for validation... Code Goes something like this... var tmpdate= document.getElementById("passport_expire_date").value; //Pick the Field Value to Validation var rgdate= new RegExp("[0-9]{2}/[0-9]{2}/[0-9]{4}"); //we need to validation date in mm-dd-yyyy format b=rgdate.test(tmpdate); if (!b) { alert("Please enter valid Passport expire date"); document.getElementById("passport_expire_date").focus(); return false; } tmpdate=tmpdate.split("/"); var mydate= new Date; if ( 1*tmpdate[0]>12 || 1*tmpdate[0]<1 || 1*tmpdate[1]>31 || 1*tmpdate[1]<1 || 1*tmpdate[2]>2100 || 1*tmpdate[2]<2005) //Check against the Validate Date, this piece can expand to validate against Leap year and more, but for me just a format is enough. { alert("Please enter valid Passport expire date"); document.getElementById("passport_expire_date").focus(); return false; } mydate.setDate(tmpdate[1]); mydate.setMonth((1 * tmpdate[0] )- 1); mydate.setFullYear(tmpdate[2]); var today= new Date; if (today >= mydate) { alert("Your Passport is expired!!!"); document.getElementById("passport_expire_date").focus(); return false; } I hope you all enjoy this piece of code in your web form... Sumit Gupta

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home