|
JavaScript - Webtop Reference Updated: 20 March 2006
Date Validation JavaScript can validate a form data's integrity before anything is submitted back to the web server, virtually eliminating the need for wasted bandwidth (network traffic). For pedagogical purposes, let's assume we're the DMV (Department of Motor Vehicles) and we want to let people apply for a driver's license online. One important question to ask is "What is your birthday?" just to make sure they're old enough to be applying for a driver's license. But, we don't want to stick up a plain text box since some applicants might type "1/5/75" to mean January 5, 1975 (using American syntax) or May 1, 1975 (using European syntax). Of course, we shouldn't allow two-digit years since that's the cause of the Year 2000 (Y2K) bug, but that's an entirely different story. To prevent these types of misunderstandings, we'll have three pull-down menus (one for the month, another for the date, and a third for the four-digit year).
Example 2a shows the HTML code to genereate the form. There's a couple of new items you should note; the VALUE parameter in the OPTION tags are required. Without these VALUE parameters, the JavaScript function will misread the selected values and treat them as blank. Also, instead of a submit button using <INPUT TYPE=Submit>, we use TYPE=Button. In addition, we add the parameter onClick to enable the JavaScript function. This onClickparameter calls the JavaScript function shown in Example 2b, when the "Submit" button is clicked.
Example 2b shows the JavaScript function, called "checkDate", to verify the data submitted from the form is correct.
The JavaScript function takes the values submitted in the form (month, date, and year) and creates a new date object. If the date is not valid (i.e. February 31st), the new Date() method will convert the string into a valid date (if Feb 31st was submitted, the new Date() method return the date "Mar 3rd". The next thing the function does is check if the new date object created matches the original date submitted. In this case, Feb does not match Mar, so the date submitted was invalid. However, if "Jan 31st" was submitted, the function would recognize a valid date was submitted and return the appropriate message. Single-line JavaScript comments may appear after two slashes //, as in: // This is a single-lined commentMulti-lined JavaScript comments may appear between between /* and */, such as: /* This is aIt's good programming to liberally code programs you write in case you need to review the material in the future. Also, if you would like to show others your code, commenting can help them see the logic behind your programming.
Disclaimer |
||||||||||||||||||||||||||||||