Form Validation

When processing a form, it's important to verify that the information provided by the user is correct:

Alert boxes or color changes can be used to inform the user of incorrect input.

A sample form for today's lecture

Example: Name Validation

<form name = "easyform" ...  >
  ...
  Please enter your name:
  <input type = "text" name = "yourname">
  ... other inputs here
</form>

The contents of the name field: document.easyform.yourname.value

To check whether the name field is blank:

if (the name text box is blank ) {
     Show an alert with a reminder message 
     Form is not done yet
} else { 
     Form is done
}

English JavaScript
The name text box is blank document.easyform.yourname.value == ""
Show alert with reminder message alert("Please provide your name.");
Form is done return true;
Form is not done yet return false;
<head> 
<script type="text/JavaScript">
function validName () {
  if (document.easyform.yourname.value == "") { 
    alert("Please provide your name."); 
    return false;
  } else { 
    return true; 
  }
} 
</script> 
</head> 

validName() is a fruitful function that returns a boolean value:

Using the validName() function in validation

Default behavior of the submit button: send the form's fields to the server when clicked:

<input type = "submit" 
       value = "Click Here to Submit"
       onClick = "return true;">

New behavior with validation: if the name field is filled in, send the form's fields to the server, otherwise do not submit the form:

onClick="if (validName() == true) {
            return true;   /* submit the form */
         } else {
            return false;  /* don't submit the form */
         }"

This code can be simplified to:

onClick = "return validName();"

The full code for the submit button:

<input type = "submit" 
       value = "Click Here to Submit"              
       onClick = "return validName();">
Exercise:

Here is the form with name validation. This page has a second copy of the form that is an exact duplicate of the first except for its name. Does name validation work on the second form? Why or why not?

The onSubmit Event

When a form is submitted, a submit event is generated, associated with the form itself. We can validate a form by defining an onSubmit event handler:

<form name     = "easyform"
      method   = "post"
      action   = "http://cs.wellesley.edu/cgi-bin/eform.cgi" 
      onSubmit = "return validName();" >

NOTE: You only need to call validName() once, either

Not in both!

Year Validation

<form name = "easyform" ...  >
  ...
  <p>Please enter your birth year: 
  <input type = "text" size = "5" name = "birthyear">
  ... 
</form>

Check that the user entered a valid year that is in the range from 1900-current year.

The contents of the year field: document.easyform.birthyear.value

Test for a valid year with the following boolean function:

function validBirthYear() {
  var year = parseInt(document.easyform.birthyear.value); 
  var currentYear = (new Date()).getFullYear();
  if ((year >= 1900) && (year <= currentYear)) {
    return true;
  } else {
    alert("Please provide a valid birth year\n" 
          + "(in the range 1900 - current year)")
    return false;
  }
} 

To validate only the year field:

<input type = "submit" 
       value = "Click Here to Submit"              
       onClick = "return validBirthYear();">

The form with year validation

Combining Name and Year Validation

To validate multiple fields in a form, we can define a boolean function validForm() that returns true when all the fields are validated and returns false otherwise:

function validForm () {
   var nameOK = validName();
   var yearOK = validBirthYear();
   return nameOK && yearOK;
} 

The onClick event handler for the submit button can call the validForm() function:

<input type = "submit" 
       value = "Click Here to Submit"              
       onClick = "return validForm();">

A form that uses the above validForm() function

Why did we not use the following, more compact approach?

function validForm () {
   return validName() && validBirthYear();
}

Validating Menus

A pull-down menu has a property named selectedIndex, whose value is the number (starting from 0) of the menu item selected, for example:

document.easyform.location.selectedIndex menu choice
0 Choose one
1 Science Center
2 Jewitt
3 Pendleton
4 Founders
Exercise:

Define a JavaScript function validLocation() to check that a valid location has been selected, and modify the validForm() function to use validLocation().

Validating Radio Buttons

<p>What is your class year?<br>
<input type = "radio" name = "graduation" value = "2010"> 2010
<input type = "radio" name = "graduation" value = "2011"> 2011
<input type = "radio" name = "graduation" value = "2012"> 2012
<input type = "radio" name = "graduation" value = "2013"> 2013 

The radio buttons all have the same name, because they belong to the same group!

Radio buttons have a checked property that is true if they are selected:

Is the year 2010 selected? document.easyform.graduation[0].checked
Is the year 2011 selected? document.easyform.graduation[1].checked
Is the year 2012 selected? document.easyform.graduation[2].checked
Is the year 2013 selected? document.easyform.graduation[3].checked

Radio buttons are validated to make sure the user has selected one:

function validGraduation() {
   if (document.easyform.graduation[0].checked ||
       document.easyform.graduation[1].checked ||
       document.easyform.graduation[2].checked ||
       document.easyform.graduation[3].checked)
   {
       return true;
   } else {
       alert("Please select a class year");
       return false;
   }
}       

Validating Checkboxes

<p>What were your favorite things about Wellesley? (Choose 1 to 3):
<ol start="0">
    <li><input type="checkbox" name="favs" value="friends"> close friends
    <li><input type="checkbox" name="favs" value="profs"> awesome professors
    <li><input type="checkbox" name="favs" value="classes"> exciting classes
    <li><input type="checkbox" name="favs" value="sports"> great sports teams
    <li><input type="checkbox" name="favs" value="clubs"> clubs, orgs, and 
                  other extra-curricular things
    <li><input type="checkbox" name="favs" value="boston"> proximity to Boston 
                  (Harvard, MIT ...)
    <li><input type="checkbox" name="favs" value="women"> women's college
</ol>

The state of a checkbox can be assessed in the same way as a radio button.

Did the user check "exciting classes"? document.easyform.favs[2].checked

The user is asked to "Choose 1 to 3" favorite things about Wellesley. How can we count the number of checkboxes that are checked? Complete the definition of a function countFavs() to perform this task:

function countFavs() {








}

function validFavs() {
    var numFavs = countFavs();
    if ((numFavs >= 1) && (numFavs <= 3)) {
       return true;
    } else {
       alert("Please select 1 to 3 favorite things");
       return false;
    }
}                                     

Putting It All Together

We can now write a function that validates all the fields of our form:

function validForm () {
   var nameOK = validName();
   var yearOK = validBirthYear();
   var locationOK = validLocation();
   var graduationOK = validGraduation();
   var favsOK = validFavs(); 
   return nameOK && yearOK && locationOK && graduationOK && favsOK;
}

Display a message when the form is successfully filled out:

function validForm () {
   var nameOK = validName();
   var yearOK = validBirthYear();
   var locationOK = validLocation();
   var graduationOK = validGraduation();
   var favsOK = validFavs(); 
   if (nameOK && yearOK && locationOK && graduationOK && favsOK)
      alert("Thanks for filling out the form!");
      return true;
   } else {
      return false;
   }  
}
Try these forms: