Validating an form fields by name

Usually you will only have a few fields to validate, and they may require a different procedure too. Rather than looping through the entire form array, you could pass the form object to a validating function and define a number of if statements for the form fields you wish to validate.

Example:

1. (validated, text)

2. (not validated)

3. (validated, number)

4. (validated, checked)
option 1   
option 2   
option 3   



The code:

<script type="text/javascript">
<!--

function validateForm(form)
{
  if (form.entry1.value.length == 0)
  {
    alert("Text field 1 is required!");
    form.entry1.focus();
    return false;
  }

  if (form.entry3.value.length == 0)
  {
    alert("Field 3 is required and must be a number!");
    form.entry3.focus();
    form.entry3.value = "";
    return false;
  }
  else if (isNaN(form.entry3.value))
  {
    alert("Field 3 must be a number!");
    form.entry3.focus();
    form.entry3.value = "";
    return false;
  }

  var boxChecked = 0;
  for (var i = 0; i < form.entry4.length; ++i)
  {
    if (form.entry4[i].checked)
    {
      ++boxChecked;
    }
  }
  if(boxChecked == 0)
  {
    alert("You must select at least 1 option in Field 4!");
    form.entry3.focus();
    return false;
  }
  return true;    
}
  
//-->
</script>