Guide to HTML, CSS and JavsScript (University at Buffalo Version)


Chapter 11: Adding JavaScript Validation to Your Web Form Page

Not all browsers support HTML5 and even those that do, may not support the HTML5 form features for required input fields, input data types, or data validation.

You may still need to utilize JavaScript to manage your form validation. To tell the browser to invoke your JavaScript function you would add the onsubmit="return validFirstName();" attribute to your <form> tag.

A very simple JavaScript function to check whether a given field (such as *firstName*) in a form (such as *myForm*) is empty would be:

function validFirstName() {
  // get the value entered for firstName and store it
  // in a local variable
  var fName = document.forms["myForm","firstName"].value;
  if (fName == null || fName == "") {
    alert("Please enter your First Name");
    document.firstName.focus();
    return false;
  }
}

Figure 11-1: JavaScript "Validation" Function

Of course, you would want to validate more than just the first name field so you would have a more complex JavaScript function (for example validateForm()) and have that function call separate functions (such as validFirstName(), validLastName(), etc.) to validate each field spearately.

Task - Add JavaScript Validation to Your Web Form Page

For this task you should create a new web page file just as you did in previous tasks. This web page should build on your Web Page Form task and use JavaScript functions to include the following:

  1. The current date and time
  2. Display a set of radio buttons that allow the user to change the background color of the web page by clicking on the desired radio button
  3. Validate the form fields according to these validation rules:
    • First Name and Last Name are not empty
    • Zip Code is either:
      • only 5 numbers
        or
        in the format 99999-9999
    • Phone Number is either:
      • only 10 numbers
        or
        in the format (999) 999-9999
    • Email has one and only one @ character, has at least one character before the '@' character, and has at least one character and a dot and at least 2 characters after the '@' sign.
      • valid: gerland@buffalo.edu
      • not valid: gerland.buffalo.edu
      • not valid: gerlandbuffalo.edu
      • valid: @buffalo.edu
    • Pop up a JavaScript alert window advising the user exactly what field did not pass the validation checks
    • Place the cursor back in the invalid field after the user clicks the OK button on the alert window if there is a validation problem.

This web page should also have a link back to your Home Page task web page.

You should then add an <a> (anchor) tag to your Home Page web page that opens your advanced CSS web page.

Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Copyright © 2017 Jim Gerland