Home » Web Development » 05 - Client Side Scripting Concepts
5

The Javascript Validate Function

How to use the validate function in javascript

The form element in register.htm is named 'register'. Each field has a name. The Javascript function validate() traverses through each form field and checks if it has a valid value. If the field is invalid or empty, form submission does not take place. This is accomplished by a 'return false' statement that stops execution of the function midway and sends control back to the caller with the output parameter set to 'false'. The 'false' value for the output parameter halts form submission. Also, the alert() command in Javascript is used to relay a message regarding invalid entry to the user. Conditional loops or 'if' loops are used to direct the function to do one set of things if a certain condition exists and other things if the condition is not satisfied. Let us look at the first section of the function.


function validate(){

validField = /^[A-Za-z][\w\-]{5,}$/;
loginStr = document.forms.register.login.value;
if (validField.test(loginStr) == false)
  {
      alert("Login Name has to start with a letter, contain only alphabets, numbers,
          underscore, or hyphen and has to be at least six characters in length");
      return false;
   }

The above fragment contains the function declaration. Note that the entire function should be contained within a pair of curly brackets.

First, we initialize the regular expression and put it into the 'validField' variable. A variable is an entity that contains a value of a specified data or object type. Data types include string, number, character, date, and so on. The value in the variable may be set to something initially and later changed using the variable name. Here, our variable validField contains a regular expression object. It is initially set to the pattern we want to match for our login name. Javascript does not require explicit declaration of variables; we may simply start using a variable by setting it equal to a value.

Next, we set a string variable called 'loginStr' to equal the DOM object that refers to the value of the 'login' text input field in the form with the name 'register'(document.forms.register.login.value).

Finally, we use the 'test' method that belongs to the regular expression object to see if the value contained in the login field fits the pattern we specified. The test method (of the general form regularexpression.test(somestring) )returns true if the pattern is found and false if the pattern is not found.

Take a look at the syntax used to make the conditional statement. All the statements to execute if the condition is satisfiedare enclosed in curly braces. Also, '==' is used to test equality. Be sure and enter this rather than a single equals symbol within conditional statements.

If the login input field does not match our requirement, we send a message indicating this to the user by means of the "alert" command. The alert Javascript command pops up a little box that contains the message specified within brackets on the broswer.

We return from the function with the output flag set to false so that form submission is cancelled if the pattern match returned false.

Sections very similar to the one above are used to validate the other text fields - password, last name, first name, and phone number. In fact, the only difference between these sections is the content of the regular expression and the message sent to the user.

Screenshot 5b: Form Validation

Screenshot 5b: Form Validation

Other sections in the validate function check if the two passwords entered by the user match each other, and if the user has selected gender, birthday, and favorite flowers. The following segment checks if the two passwords entered match each other. Note that '!=' is equivalent to saying 'not equals' in Javascript syntax. 'document.forms.register.password1.value' refers to the value in the field next to 'Choose a Password' while document.forms.register.password2.value refers to the value in the input field next to 'Enter Password Again".

if(document.forms.register.password1.value != document.forms.register.password2.value)
{
        alert("Passwords do not match - please enter the same password twice");
    return false;
}

The gender input field is a radio group. A radio group consists of two or more input controls of type radio that have the same name but different values. Only one of the group may be selected by the user at any point. Following is the HTML markup for the gender field:

Female <INPUT TYPE="radio" NAME="gender" VALUE="F">
Male <INPUT TYPE="radio" NAME="gender" VALUE="M">

Javascript references to radio groups are different from refernces to text input controls. The radio group becomes an array - a sequence of values, each accessible by an index that indicates its position in the sequence stored contiguously in memory. For a radio group, each member of the group may be accessed using index[number_in_group] where number_in_group is the relative position of the member. The radio group member that occurs first is referenced by index[0], the 1st by index[1] and so on. The final member is referenced by index[count-1], where count is the total number of members in the group. Javascript holds the count of members in a group in the 'length' property. A 'checked' property indicates if the member is selected or not. The gender group contains two members. The member with value='F' is contained in document.forms.register.gender.index[0] and the member whose value is 'M' is contained in document.forms.register.gender.index[1]. Both members are initially unchecked; document.forms.register.gender.index[n].checked is set to false.

genderSelect = false;
for (i=0;i < document.forms.register.gender.length;i++)
{
   if (document.forms.register.gender[i].checked == true)
    {
        genderSelect = true;
     }

 }
 if (genderSelect == false)
 {
   alert("please select gender")
   return false;
 }

In order to check if the user has selected a gender, we loop through all the members of the group and check if any one member is checked.

Initially, a boolean variable called genderSelect is set to false.

The for loop takes the following form: for(counter=initial value; while counter satisfies condition; increment or decrement counter). All the statements that are executed for each iteration through the loop should be enclosed in curly braces. The above loop is executed for every integer value of i (the counter) between zero and the length of the gender radio group. The counter is incremented and the loop is executed as long as the counter i holds a value that is less than document.forms.register.gender.length (here, just two times as gender's length is 2).

Inside the loop, we check to see if the radio group member referenced by index[i] is checked. If it is checked, we set the genderSelect variable to true

After the loop exits, we know that the user did not select a gender if genderSelect is still set to false; this means that the condition document.forms.register.gender[i].checked was not satisfied by any of the members in the group. If this is the case, we send an appropriate message to the user and exit with a false flag.

  
  flowerSelect = false;

for (i=0;i < document.forms.register.likes.length;i++)
{
    if (document.forms.register.likes[i].checked)
     {
        flowerSelect = true;
        break;
      }
 }

if (flowerSelect == false)
  {
    alert("Please check at least one flower that you like");
        return false;
   }

Radio groups and checkbox groups are represented in the same way in Javascript. However, only one member of a radio group may be checked at any time while more than one member of a checkbox group may be checked. The validation for the favorite flowers field checkbox group is almost identical to that of the gender radio group. However, we use a 'break' statement to exit the for loop (and thus save us a few unnecessary iterations) as soon as a checked member is found. All we need to do is make sure at least one flower is selected; we do not need to check the rest of the members once we find a checked flower.

if (document.forms.register.month.selectedIndex == 0)
{
    alert("Please Select Birth Month");
        return false;
}

if (document.forms.register.day.selectedIndex == 0)
{
    alert("Please Select Birth date");
        return false;
}

Javascript holds an array that contains all the options of a select control. This array references each option in sequence by options[sequence_number]. The sequence_number begins with zero and ends with (count of options - 1). options[sequence_number].value refers to the value specified for the option while options[sequence_number].text refers to the text that shows up on the browser for the option at position sequence_number. The selectedIndex (note the upper case 'I') property of a list box control refers to the index or sequence number of the selected option. We make sure that the selectedIndex for the month and day fields does not contain 0 . Any value greater than zero indicates that the user has made a selection as we put in an initial dummy option that simply contains the value '<-select->'. This completes our form validation function. Once all the fields are checked and marked as valid, we simply return a 'true' flag to allow form submission.

To test the validation function, go to the Registration Page and try entering different sorts of values for these fields and submitting the form. A valid submission will simply cause the register.htm file to be refreshed as we have not specified an action upon form submission as yet. You can examine the entire validation function if you view the source of this file and search for the string "function validate()"

You may notice a 'document.cookie' directive in the validate function in register.htm. Also, if you place your mouse over the navigation controls on the top right of the page, you will notice that they have become animated. On the catalogue page, a large picture of each flower will pop up if you click on either the image or the name of the flower. We will see how the Javascript is used with the HTML DOM to create these DHTML effects in the next chapter.