Validating a particular form field onsubmit

The best way to validate a required form field is via the onsubmit event handler. The onsubmit attribute can be set in the tag of an <input> tag or, as in the following example, in the <form> tag.

<form name="form1" onsubmit="return validateForm(this.text1);"
action="http://cgi-cmsc.cs.uchicago.edu/~sterner/cs101/hw6/reflector.cgi" method="post">

<input type="text" name="text1" size="10" maxlength="10">

<input type="submit" name="submitButton" value="Submit">
</form>

The function call may be a little confusing at first sight,

onsubmit="return validateForm(this.text1);"

but it's a simple way of passing on a value. The event handler onsubmit returns to the main program execution the return value of the function validateForm( ). If the function returns true, the program continues and the form is submitted. If it returns false, the onsubmit event is interrupted.

The value passed to the function validateForm( ) is the input field object whose name is "text1". "this" refers to the object from which the function is called, the form object "form1" in this case. It's a shorthand way of referring to the "current object". The following three object references are equivalent, any one could be used:

this.text1
document.forms[0].elements[0]
document.forms['form1'].elements['text1']

Example:




Function code:

  <script type="text/javascript">
  <!--
  
  function validateForm(field)
  {   
    if (field.value.length == 0)
      {
      alert("Entry field " + field.name + " is required.");
      field.focus();
      field.select();
      return false;
    }
    return true;
  }

  //-->
  </script>