In the first part of this series I introduced various forms of validation including some best practices, the difference between client-side and server-side validation, the types of validation including separation and indications for required fields, correct format, and confirmation fields.

Create a simple form

If you have never created web forms with validation then I invite you to follow along with this tutorial for creating a simple form that will perform validation of several different text fields and one text area field on a web page. I am utilizing Dreamweaver and its Validate Form Behavior in my example here; however, any web editing tool can be used to accomplish the same tasks with similar results using the code snippets provided. Note that the JavaScript portion might be a bit trickier without the tool, so I’ve included that code as well at the end of this tutorial. In this simple form, no actual data will be submitted; we’re only testing it for validation purposes.

Create a simple form with client-side validation: Step-by step

  1. Create a new blank HTML document.
  2. Insert a form into the web page document (Insert | Form | Form) adding the following code:
    <form action=”” method=”get”></form>
  3. Click inside the form between the opening and closing tags, then hit Enter several times to create several lines of empty space and then go back to the second empty line in the form and indent once (Ctrl+Alt+]).
  4. At this line inside the form type Name:
  5. Hit Shift-Enter to create a line break, <br />, then hit Enter once to move the cursor insertion point one line down.
  6. Insert a text field into the form (Insert | Form | Text Field).
  7. In the Tag Editor input for the text field you just created, for the Name enter NameField where the resulting code will be name=”NameField” in the appropriate box, and click OK; this adds the following code:
    <input name=”NameField” type=”text” />
  8. Create two line breaks: <br /><br />
  9. Place the insertion point two lines below the Name text field you just created.
  10. Type Please enter an email address.
  11. Create a line break then hit Enter once to move the cursor insertion point one line down.
  12. Insert another text field (Insert | Form | Text Field) and in the name box enter EmailAddressField to name this field, which adds the following code:
    <input name=”EmailAddressField” type=”text” />
  13. Create two line breaks <br /><br />.
  14. Hit Enter twice to place the cursor insertion point two lines below the Email text field you just created.
  15. Type Enter a Comment: and create a line break <br/>.
  16. Insert a multi-line text field into the form (Insert | Form | Text Area) and in the name box enter CommentField to name this field, with 50 columns and 8 rows, adding the following code:
    <textarea name=”CommentField” cols=”50″ rows=”8″></textarea>
  17. Create two line breaks <br /><br />.
  18. Hit Enter twice to place the cursor insertion point two lines below the text area field you just created.
  19. Making sure your insertion point is still inside the form, insert a Submit button (Insert | Form | Button), and select Submit for the type selection from the pull-down menu, then name it SubmitButton, adding the following code:
    <input name=”SubmitButton” type=”submit” />
  20. Save the document.

The entire form code should look like this:

<form action="" method="get">
Name:<br />
<input name="NameField" type="text" /><br /><br />
Please enter an email address:<br />
<input name="EmailAddressField" type="text" /><br /><br />
Enter a Comment:<br />
<textarea name="CommentField" cols="50" rows="8"></textarea><br /><br />
<input name="SubmitButton" type="submit" />

And when rendered in the browser the simple form takes on this appearance as shown in Figure A:

Add the validation

Now we need to add the Validate Form Behavior to the <form> tag’s onSubmit event for the client-side validation. In layman’s terms, this means that we must tell the web authoring tool (Dreamweaver) when to check the form fields for valid data entry. In this case, we will tell Dreamweaver to execute the validation when the user clicks the Submit button in the form, utilizing the JavaScript “onSubmit” event for the client-side validation.

1. In Dreamweaver Design View, click anywhere in the form.

2. In the lower left area of the Document window, click on the <form> tag in the Tag Selector to select the form. Another way to do this is by selecting the form by clicking on the dashed red line that outlines the form in the Document window as in Figure B:

3. Open the Behaviors panel (Window | Behaviors) and in the list of Events on the left side of the panel, choose onSubmit from the drop-down list (see Figure C; click to enlarge). You may have to click on the Show all events button in the Behaviors panel to display a list of events for the Form tag. If this is the case, then simply choose onSubmit from the drop-down list.

Figure C

4. With the onSubmit event selected in the Events dropdown list, click on the Add Behavior (+) button and select Validate Form from the list. In the dialog box that appears, click on the topmost field named NameField to highlight it.

5. Now we can specify the validation parameters for this field. Click in the Required checkbox under the Value: category to make this a required field.

6. With the NameField field still highlighted, click the Anything radio button under the Accept category; this will allow any characters to be accepted, as shown in Figure D:

7. You can specify validation criteria for the remaining fields by highlighting each of the other field names listed in the “Named fields:” box and repeating steps 4, 5, and 6 above. If you’re following this example then make the second field (i.e., “EmailAddressField”) a required field that will only accept an email address, and make it a required field, and make the third field (i.e., “CommentField”) an optional field that may contain anything.

8. When you’re done specifying the validation criteria for all three fields, click “OK.”

9. Save your page and then preview in a web browser.

10. Test the validation routines by entering different values in the fields and clicking the Submit button. Also, try leaving one or more of the required fields blank and click the Submit button. You should get popup error messages that describe what the problem is and what data is expected for each of the validated fields.

11. Now, let’s clean up the form a bit and add our instructions for the required fields with the following statement placed before the form area: Fields marked with an asterisk (*) are required. Also add your asterisks to each of the required field names.

The final simple form with validation code including the JavaScript looks like this:

<script type="text/javascript">
function MM_validateForm() { //v4.0
  if (document.getElementById){
    var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
    for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]);
      if (val) {; if ((val=val.value)!="") {
        if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
          if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain a valid e-mail address.\n';
        } else if (test!='R') { num = parseFloat(val);
          if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
          if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
            min=test.substring(8,p); max=test.substring(p+1);
            if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
      } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
    } if (errors) alert('The following error(s) occurred:\n'+errors);
    document.MM_returnValue = (errors == '');
} }
<p><strong>Simple form example</strong></p>
<p><em>Fields marked with an asterisk (*) are required</em></p>
<form action="" method="get" onsubmit="MM_validateForm('NameField','','R');MM_validateForm('EmailAddressField','','RisEmail');MM_validateForm('CommentField','');return document.MM_returnValue">
Name*:<br />
<input name="NameField" type="text" id="NameField" />
<br />
<br />
Please enter an email address*:<br />
<input name="EmailAddressField" type="text" id="EmailAddressField" />
<br /><br />
Enter a Comment:<br />
<textarea name="CommentField" cols="50" rows="8" id="CommentField"></textarea>
<br /><br />
<input name="SubmitButton" type="submit" />

The final simple form with validation is displayed in Figure E:

Further notes on testing and revising rules

The simple form with validation in this example does not actually submit any form data since we left the “action” attribute in the <form> tag blank (<form action=””); if this were an actual form that you wanted to use on the web, then one way to get it working would be to specify the URL of a CGI script in the action attribute in the <form> tag. In this tutorial and example we are only interested in the validation routines, and not where the actual form data will be submitted.

When the validation rules are finally satisfied and the form submission is successful, the popup error message(s) will cease and depending on your Internet browser you may encounter a “404 File Not Found” or similar message when the form is submitted due to the empty “action” attribute in the <form> tag. On the other hand, it may appear that nothing happens at all when the form submission is successful. However, for our purposes, the absence of any popup error message(s) upon form submission indicates that the form submission was indeed successful, i.e., the data entered into the form passed all of the script validation test(s).

To revise an existing validation rule, right-click on the onSubmit – Validate Form event/behavior line in the Behaviors panel and select Edit Behavior from the popup menu. The Validate Form dialog box will appear, and you can then make changes to the existing validation rules.

In the case where a single web page may be containing multiple forms, you must be certain that you’ve selected the proper field in the Named fields: list in the Validate Form dialog box before applying any validation rule(s). If you’re not careful when applying validation rules to fields in web pages containing multiple forms you may inadvertently add a validation rule to another existing form. The way to get around this is to be sure that all forms on the same web page have unique names for each field. In the case of the name field it could be indicated individually by name=”Form1NameField”, and name=”Form2NameField”, etc…

Dreamweaver’s built-in Validate Form Behavior gives you the ability to quickly set up validation rules for form text fields without having to know much about tricky JavaScript coding. While this tool is great, it does have limited capability and functionality, so in a future installment of the series, I will demonstrate the use of another client-side validation tool known as the Check Form extension, available for Dreamweaver. It is a free, downloadable plug-in tool that allows for more advanced client-side validation for web forms.