Javascript Form Validation

JavaScript can be used to validate data in forms before the data is submitted. This is quite effective and user friendly. There is nothing more irritating to a user than filling out a long form, submitting the form, receiving an error, then hitting the back button and all the data is gone.

This article shows you how to validate form data before the form is submitted using Javascript.

Javascript

This is the code that performs the data validation.

<script type="text/javascript">
function ValidateForm (form) {
  var msg;
  var errors = "";
  form.sbutton.disabled=true;
  if (form.field1.value=="" || form.field1.value==null) {
    errors += "-- Field 1 not entered\n";
  }
  if (form.field2.value=="" || form.field2.value==null) {
    errors += "-- Field 2 not entered\n";
  }
  if (form.field3.value=="" || form.field3.value==null) {
    errors += "-- Field 3 not entered\n";
  }
  if(errors) {
    msg = "Request not processed because of the following error(s).\n";
    msg += errors;
    msg += "\nPlease correct the error(s) and try again.\n\n";
    alert(msg);
    form.sbutton.disabled = false;
    return false;
  } else {
    return true;
  }
}
</script>

HTML Code

This is the code to build the form.

<form method="post" onsubmit="return ValidateForm(this);">
  Field 1: <input type="text" name="field1" size="20" />
  <br />
  Field 2: <input type="text" name="field2" size="20" />
  <br />
  Field 3: <input type="text" name="field3" size="20" />
  <p><input name="sbutton" type="submit" value="Submit" /></p>
</form>

Full Example

Copy and paste this code into your HTML editor and try if for yourself.

<html>
<head>
<title>Form Validation</title>
</head>

<body>

<form method="post" onsubmit="return ValidateForm(this);">
  Field 1: <input type="text" name="field1" size="20" />
  <br />
  Field 2: <input type="text" name="field2" size="20" />
  <br />
  Field 3: <input type="text" name="field3" size="20" />
  <p><input name="sbutton" type="submit" value="Submit" class="button" /></p>
</form>

<script type="text/javascript">
function ValidateForm (form) {
  var msg;
  var errors = "";
  form.sbutton.disabled=true;
  if (form.field1.value=="" || form.field1.value==null) {
    errors += "- Field 1 not entered\n";
  }
  if (form.field2.value=="" || form.field2.value==null) {
    errors += "- Field 2 not entered\n";
  }
  if (form.field3.value=="" || form.field3.value==null) {
    errors += "- Field 3 not entered\n";
  }
  if(errors) {
    msg = "Request not processed because of the following error(s).\n\n";
    msg += errors;
    msg += "\nPlease correct the error(s) and try again.\n\n";
    alert(msg);
    form.sbutton.disabled = false;
    return false;
  } else {
    return true;
  }
}
</script>

</body>
</html>

posted August 22, 2009 in Javascript