JS Exercise 21: Form Validation Using JavaScript

Assignments
Bottom

Exercise: Form Validation Using JavaScript

Try the form validation script

1. View this CGI form: CGI with Form Validation
2. Click the Submit button without entering any data. Pay attention to the error messages.
3. Type your name in the Name text box. Click the Submit button again. Pay attention to the error message.
4. Type your name in the "Email Address" text box. Click the Submit button again. Pay attention to this error message.
5. Type a valid email address. Click the Submit button again. This time, the form should be submitted.

Insert the form validation script with your form

1. Download js21.html: Right click this link. Choose "Save Target As." Save the file to a local folder: js21.html
2. View js21.html in CoffeeCup.
3. Copy the <script> element to the <head> section of the web page with the form.
4. The opening <form> tag should look like this, but use your own form name:
<form name="demo" onsubmit="return ValidateForm()">

5. Copy and paste this <input> element to create a text box for email address:
<input type="text" name="Email" size=30 onblur="checkEmail(document.forms.demo.Email)" />

6. In the event handler, change the form name from "demo" to the name of your form.
7. At least one other form element must be required; that is, cannot be blank. Copy and paste this <input> element to create a required text box:
<input type="text" name="Name" size=30 onblur="checkEmpty(document.forms.demo.Name)" />

8. The form element above creates a text box named Name ("Name" appears in the alert message, so capitalize the name of the form element).

9. You may add other required form elements, just create a unique, capitalized name for each.

Tip: To add red asterisks, use this <span> tag:
<span style="color:red">*

10. Edit the function ValidateForm() to work with your form: Change "demo" to the name of your form in the two statements shown below.

function ValidateForm() {
    var FormErrors=0;
     if (!checkEmail(document.forms.demo.Email)) {
         FormErrors+=1
     }
     if (!checkEmpty(document.forms.demo.Name)) {
         FormErrors+= 1
     }


11. If you created additional required form elements, copy and paste this line in the function ValidateForm(). Change "demo" to the name of your form, and change Name to the name of the form element.
     if (!checkEmpty(document.forms.demo.Name)) {
         FormErrors+= 1
     }

Top
Assignments