Validating Input at the Client: check for blank required fields

Page content


The code below is for a text input field, a submit button and a DIV tag that we could use in lieu of an alert box for notifying the user that the input field is required. The code uses the onblur event to determine if the input box is blank and notify the user that this is a required field.

Note: The style properties in this example are set for convenience but are not required.

Code view

Username <input name=“userName” type=“text” id=“userName” style=“display:block;margin-top:5px;margin-bottom:5px;” onblur=’’" />

Set the onBlur

Case 1: in the tag code

Here we don’t need a script block. Instead, the JavaScript code is written right in the onblur attribute of the text input tag definition.It may be difficlut to see but this is the string:

..onblur=’ if(this.value=="")


document.getElementById(“messageDiv”)" is a required field!"} '

Code view


Case 2: with the Document Object Model (DOM) and JavaScript

The code below uses the getElementById(tagID) DOM method and assigns onblur as an anonymous function object. This is useful in checking for several required fields being blank and alerting the user. Here’s what the code looks like in Code View (HTML View). You can switch to Display View to see what it looks like to the user.

Code view


These examples above show you how to use JavaScript and the Document Object Model (DOM) to change elements on a page. In this case, to validate form data and display a message to the user.

Validating input at the client reduces unnecessary round trips to the server and is a cost-effective way of minimizing bandwidth usage and CPU utilization. In addition to checking for blanks, we might want to check formats and trim leading and trailing spaces and extra linefeeds. These topics will be covered in other articles dealing with Web Development. You can visit the Web Development Channel for more articles about using the Document Object Model (DOM) and JavaScript.

This post is part of the series: Web Design using DHTML and the DOM

Creating web sites with DHTML based on the DOM can increase server performance, lower bandiwdth utilization and solve most cross-browser compatibility issues.

  1. Getting Elements Using the HTML DOM and JavaScript
  2. Applying Events to DHTML Web Pages Using Javascript and the DOM
  3. Validating Input at the Client: Check for blank or required fields
  4. Validating Input at the Client: trim the field
  5. Validating Input at the Client: check numeric value fields
  6. Leveraging CSS Styles
  7. DOM getElementsByTagName Method for Bulk Element Formating
  8. Unraveling the JavaScript Switch Statement