Validating with onchange

Any event handler can trigger form validation. You can use onchange if you want to validate a particular field that is not required. onchange only kicks in if the field value changes. If it's empty and remains empty, no validation will take place since the value doesn't change.

<input type="text" name="text1" size="20" maxlength="20" tabindex="1" 
value="(delete this)" onchange="return validateForm(this)" />

Example:

Enter some data:

1. (validates "onchange": delete any content and select field 2)
2. (no validation)



Code:

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

function validateForm(field)
{   
  if (field.value.length == 0)
  {
    alert("Entry field " + field.name + " is not required,\n but recommended.");
    return false;
  }
  return true;
}

//-->
</script>