JavaScript Samples: Form Validation Part 1

The Functions:

Place the JavaScript Functions in the <head> element of your page:

Note: validate_required() needs 2 pieces of information to run: the form field (field), and a warning message (alertTxt) if it is not valid.

null is a non-existant number and “” means there is nothing in the field (they are not exactly the same). The if (value==null || value==””) means if the value is null OR there is an empty string.

<script type="text/javascript">
<!--
// Required Fields - 
function validate_required(field, alertTxt){
 with (field) {
  if (value==null || value=="") {
   alert(alertTxt);
   return false;
  }
  else {
   return true;
  }
 }
}
// Validate Email - Make sure email is in proper format
function validate_email(field,alerttxt)
{
with (field)
  {
  apos=value.indexOf("@");
  dotpos=value.lastIndexOf(".");
  if (apos<1||dotpos-apos<2)
    {alert(alerttxt);return false;}
  else {return true;}
  }
}

/* Validate the entire form *
*/
function validate_form(thisform) {
 with (thisform) {
  if (validate_required(name, "You forgot to add your name")==false) {
   name.focus();
   return false;
  }
  else if (validate_required(email, "You forgot to add your email address")==false) {
   email.focus();
   return false;
  }
  else if (validate_email(email, "Your email is in an incorrect format")==false)
  {
   email.focus();
   return false;
  }
 }
}
-->
</script>
</head>
<body>
<h1>JavaScript: Contact Us</h1>
<p>Please let us know what you're thinking. Drop us a note, say 'hi,' ask any question.</p>
<p><em>* Denotes Required Field</em></p>

<form action="contactUs.php" onsubmit="return validate_form(this)" method="post">
<p>* Name:</p>
<p><input type="text" id="name" name="name" value="your name" /></p>
<p>Age:</p>
<p><input type="text" id="age" name="age" value="your age" /></p>
<p>* Email:</p>
<p><input type="text" id="email" name="email" value="your email" /></p>
<p>Comments:</p>
<p><textarea id="comments" name="comments" rows="5" cols="40">Add your comments here</textarea></p>
<p><input type="submit" />&nbsp;&nbsp;<input type="reset" />
</form>

</body>
</html>