Validating forms


First name:
Last name:

Comment:

Try to submit the above form. Notice that it can't be submitted if one of the fields is left blank. Only if all the fields are filled in, it will be submitted to the e-mail address you provided when the page was loading.
If you have a form on your page, wouldn't you like to prevent it from being submitted if its clue fields aren't filled in, or are obviously filled in incorrectly?
This week you will learn how to do that. Let's see the source of the above example:

<script languge="JavaScript"> <!-- function testForm1() { if (document.form1.First_name.value!=""&&document.form1.Last_name.value!=""&&document.form1.Comment.value!="") return true; alert("\nForm submission canceled due to one or more empty fields.\n\nPlease fill in all the fields."); return false; } // --> </script> <form name="form1" method="post" action="your mailing cgi-script" onSubmit="return testForm1()"> First name: <input name="First_name" size=30> <br>Last name: <input name="Last_name" size=30> <br><br>Comment: <br><textarea rows=4 cols=30 wrap name="Comment"></textarea> <br><br><input type="submit" value="Submit"> <input name="MAIL" value="your@email.here" type="hidden"> <input name="SUBJECT" value="Weekly new JavaScript technique: example 1" type="hidden"> </form> Note the onSubmit="return testForm1()" part of the <form> tag.
A submit event occurs when a user submits a form. The onSubmit event handler executes JavaScript code when a submit event occurs.
To prevent a form from being submitted, a return statement that returns false must be assigned to the event handler. Any other returned value lets the form submit. If you omit the return statement, the form is submitted. So, unless the function testForm1() returns false, the form will be submitted. Functions are defined, as said in the first week, within the <script> tag. The testForm1() is a simple function that returns true if all the fields values are different from empty string. Otherwise, the alert dialog box pops up and the function returs false, which causes the form not to be submitted. Basically, to suit your needs, in the above example you should just change the line if (document.form1.First_name.value!=""&&document.form1.Last_name.value!=""&&document.form1.Comment.value!="") so that you instead of First_name, Second_name and Comments put the names of your input and/or textarea fields.

Here you can also see the sintax of JavaScript language: && is logical AND operator, || is logical OR operator and ! is logical NOT operator. != means different from whereas == means the same as. Blocks are enclosed within { and }. Generally, if you know C, you shouldn't have any problem understanding it.




More complex examples

Now we'll have a form where the user submits his/her date of birth in a specific format and his/her e-mail address. When the user submits the form, the script will prevent the form from being submitted if specific terms are not met: e-mail must have characters '@', '.' and must not have any blanks ' '; the given date format must be met.
E-mail address:

Date of birth: mm/dd/yyyy     
The source of the above example: <script languge="JavaScript"> <!-- function testForm2() { var bd=document.form2.birth_date.value; var em=document.form2.e_mail.value; if (bd==""||em=="") { alert("\nForm submission canceled due to one or more empty fields.\n\nPlease fill in all the fields."); return false; } if (em.length<8||em.indexOf('@')==-1||em.indexOf('.')==-1||em.indexOf(' ')!=-1) { alert("\nForm submission canceled due to the unacceptable e-mail.\n\nPlease fill in all the fields correctly."); document.form2.e_mail.focus(); return false; } if (!(bd.length==10&&bd.indexOf('/')==2&&bd.indexOf('/',3)==5)) { alert("\nForm submission canceled due to the unacceptable date format.\n\nThe correct format is mm/dd/yyyy"); document.form2.birth_date.focus(); return false; } var mm=parseInt(bd.substring(0,2),10); var dd=parseInt(bd.substring(3,5),10); var yyyy=parseInt(bd.substring(6,10),10); if (isNaN(mm)||isNaN(dd)||isNaN(yyyy)||mm==0||dd==0||yyyy==0) { alert("\nNumbers are used to specify the date.\n\nForm submission canceled."); document.form2.birth_date.focus(); return false; } if (yyyy>2000) { alert("\nForm cannot be sent due to the unexistance of the sender.\n\nTry again when you are born."); document.form2.birth_date.focus(); return false; } if (yyyy<1900) { alert("\nGee, you must be a ghost.\n\nGhosts are uninvited here and are not allowed to send any forms."); document.form2.birth_date.focus(); return false; } if (mm<1||mm>12||dd<1||dd>31) { alert("\nMonths are indexed from 1 through 12.\nDays are indexed from 1 through 31.\n\nForm submission canceled."); document.form2.birth_date.focus(); return false; } return true; } // --> </script> <form name="form2" method="post" action="your mailing cgi-script" onSubmit="return testForm2()"> E-mail address: <input name=e_mail size=40> Date of birth: <i>mm/dd/yyyy</i> <input name=birth_date size=10> <input type="submit" value="Submit"> <input name="MAIL" value="your@email.here" type="hidden"> <input name="SUBJECT" value="Weekly new JavaScript technique: example 2" type="hidden"> </form> Here, the function testForm2(), that actually validates the form, consists of a set of if statements which check possible irregularities. If an irregularity is found an alert dialog box pops up, focus is given (this doesn't work in Internet Explorer 3.0 for unknown reasons) to the object which contains irregular data, and, by returning false, the form submission is canceled. If no irregularities are found, the function returns true and the form is submitted.
Firstly, we assign the values of the input fields to the variables bd and em. Both of these varibles now represent strings entered in the corresponding input fields by the user. If at least one of them is an empty string the function terminates. Otherwise, the function execution continues. The em variable is now checked. The function terminates if em has less than 8 characters, if '.' or '@' are not found (indexOf(char, start) is a method of the string object which returns the index of the first occurence of the specified character within the string; first character has index 0 and last stringName.length-1; if the character is not found the method returns -1; second argument can be passed to this method representing the index location of the string to start the search from) or if empty space ' ' is found. After that, the bd variable is checked. It is acceptable only if it has exactly 10 characters and if '/' is found at second and fifth location. If these string variables have passed all the above checks, numeric variables mm, dd and yyyy are created representing month, day and year, respectively. parseInt(string, radix) converts the string argument to an integer of the specified radix and returns that integer. The substring(A, B) method returns string variable containing characters from index A inclusive, to index B exclusive of the string object. If parseInt(string, radix) cannot succesfully convert a string to a number, on some systems it returns NaN, and on some 0. Thus, in the next check, the execution of the function testForm2() is stopped if mm or dd or yyyy equals to 0, or if any of these variables is NaN, which is checked with the isNaN(variable) function that returns true if its argument is NaN. After that, few more checks are performed with the variables mm, dd and yyyy and if everything is OK the function returns true which lets the form submit.

One more example this week:

How old are you:

You live in:
America
Europe
Australia
Asia
Africa

    
In this example, when the user sumbits the form, it is being checked whether an option is selected and whether a radio button is checked. If not, the form is not submitted. Here is the source: <script language="JavaScript"> <!-- function testForm3() { if(document.form3.years.selectedIndex==0) { alert("Form submission canceled due to the unspecified age."); return false; } var specified=false; for (var i=0;i<document.form3.continent.length;i++) if(document.form3.continent[i].checked) specified=true; if(!specified) { alert("Aliens are not allowed to send forms here."); return false; } return true; } //--> </script> <form name="form3" method="post" action="your mailing cgi-script" onSubmit="return testForm3()"> How old are you: <select name="years"> <option> <option value="0-20">less than 20 <option value="20-40">20 - 40 <option value="40-60">40 - 60 <option value="60-">more than 60 </select> <br><br> You live in: <br><input name="continent" type="radio" value="America">America <br><input name="continent" type="radio" value="Europe">Europe <br><input name="continent" type="radio" value="Australia">Australia <br><input name="continent" type="radio" value="Asia">Asia <br><input name="continent" type="radio" value="Africa">Africa <br><br><input type="submit" value="Submit"> <input type="reset" value=" Clear "> <input name="MAIL" value="your@email.here" type="hidden"> <input name="SUBJECT" value="Weekly new JavaScript technique: example 3" type="hidden"> </form> The only new things here are the selectedIndex property of the select object which is an integer specifying the index of the selected option in a select object, for loop that looks just like in other C-like languages ( for(init; condition; increment) { statements; } ) and the checked property of the radio object which is a boolean value specifying whether a radio-button is checked.


Previous technique Back to the main page



This page hosted by . Get your own Free Home Page

1