Validating Input at the Client: trim the field

Validating Input at the Client: trim the field
Page content

Introduction

Before a form is submitted, we want to check or fix input fields at the client’s browser so we don’t have to worry about it on the server. Since JavaScript doesn’t have a trim function as in vbscript, we can use a regular expression pattern and the replace method. The tag we can try this on is illustrated below. There is no need to alert the user, just trim the leading and trailing spaces (whether they are required or not) after the input loses focus or tabs to the next input field - we’ll use the onblur event and property.

Code view

Username 

Set onBlur

As soon as the user leaves the username text input, the value of the input is trimmed; removing leading and trailing spaces.

Case 1: Directly in the Tag

javascript syntax: this.value=this.value.replace(/(^\s*)|(\s*$)/g, “”);

Code view

Username 

Case 2: with Reusable Javascript

Here we use javascript to access the username input field as a DOM object and apply the onblur attribute.

Code view

Username 

For a textarea Tag

A textarea tag can be multi-line so it may be desirable to remove leading and trailing newline characters as well. Set the onblur attribute to the javascript statement below

javascript syntax :this.value= this.value.replace(/(^\s*)|(\s*$)|(^\n*)|(\n*$)/g, “”);

Code view

Textarea 

Conclusion

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 trimming fields, we might want to check for blanks and check for formats like number or date.

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