Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q1417 How can I verify that all the fields in a form are filled out?

You are here: irt.org | FAQ | JavaScript | Form | Q1417 [ previous next ]

The following was submitted by Bill Sterzenbach

Here is a chunk of code that you can use to validate all of the forms on your website. Just add the letters 'rqd' to the name of the form element, name the form 'myForm', and create a list of field names that you want to display in the dialog that notifies the user that the field is required. Only tested in Internet Explorer & Netscape Navigator 4+. I'm still tweaking it, so all feedback is appreciated.

<html>
<head>
<title>Form Field Validation</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language="JavaScript"><!--
// put this code in the head of the document to be validated//
var arNames = new Array("First Name","Last Name","Zip Code");
function Validate(arNames,FrmName) {
  if (!FrmName) {
    FrmName='myForm';
  }
  Mssge1 = 'Sorry, ';
  Mssge2 = ' is a required field.';
  var VldTxt = 0;
  var frmObj=eval('document.'+FrmName+'.elements');
  var ElNum = frmObj.length;
  for (var i=0;i<frmObj.length;i++) { // for all of the elements on the form..
    if ((frmObj[i].name.indexOf('rqd') > -1)) { // if the element has the letters 'rqd' in it's name..
      if (frmObj[i].type == 'select-one' || frmObj[i].type == 'select-multiple') { // If it's a list element(for Nav)..
        if (!frmObj[i].options[frmObj[i].selectedIndex].value) { // and if the element is empty..
          alert(Mssge1 + arNames[VldTxt] + Mssge2) //give a warning..
          frmObj[i].focus();
          return false; //return false to the form...
          break;        //exit out of the loop.
        }
      } else { // We have a regular old form field..
        if (!frmObj[i].value) {
          alert(Mssge1 + arNames[VldTxt] + Mssge2);
          frmObj[i].focus();
          return false;
          break;
        }
      }
      VldTxt++; // Increment the number of required fields based on the Rqd prefix
    }
  }
  return true;
}
//--></script>
</head>

<body bgcolor="#FFFFFF">
You form should look like this:
<form action="Oof.cfm" method="post" onSubmit="return Validate(arNames)"
name="myForm">
  First Name
  <input type="text" name="FName_rqd"><BR>
  Last Name
  <input type="text" name="LName_rqd"><BR>
  Title
  <input type="text" name="Title"><BR>
  Zip Code
  <input type="text" name="Zip_rqd"><BR>
<input type="submit" name="ert" value="LetsDoThis">
</Form>
</body>
</html>

Feedback on 'Q1417 How can I verify that all the fields in a form are filled out?'

©2018 Martin Webb