Pin Me

Validating Input at the Client: trim the field

written by: Carmelo Carbonara•edited by: Linda Richter•updated: 10/1/2008

This article provides examples of validating input fields by removing leading and trailing spaces for text input as well as removing leading and trailing linefeeds in textareas.

  • slide 1 of 4

    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&nbsp;<input name="userName" type="text" id="userName" style="display:block;margin-top:5px;margin-bottom:5px;" onblur=' ' />

  • slide 2 of 4

    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&nbsp;<input name="userName" type="text" id="userName" style="display:block;margin-top:5px;margin-bottom:5px;" onblur=' this.value=this.value.replace(/(^\s*)|(\s*$)/g, "") ; ' />

    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&nbsp;<input name="userName" type="text" id="userName" style="display:block;margin-top:5px;margin-bottom:5px;" onblur=' ' />

    <script language="JavaScript" type="text/javascript">

    function myObj(tagID){return document.getElementById(tagID) ; };

    trim=function(){this.value=this.value.replace(/(^\s*)|(\s*$)/g, "");}

    myObj("userName").onblur=trim

    </script>

  • slide 3 of 4

    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&nbsp;<textarea name="textField" cols="30" rows="10" id="textField" onblur=' this.value=this.value.replace(/(^\s*)|(\s*$)|(^\n*)|(\n*$)/g, ""); '></textarea>

  • slide 4 of 4

    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.