Removing Leading/Trailing Blanks

Question: I have input fields on a form that I want to make mandatory but my visitors insist on entering blanks to bypass the field length test I am using. Is there an easy way to remove leading and trailing blanks from whatever is input so that I can validate the real content of the field instead of strings of blanks?

Answer: The following Javascript function will take any value passed to it and return the field with the leading and trailing blanks removed:

function stp(fld) {
var res = "";
var c = 0;
for (i=0; i<fld.length; i++) {
  if (fld.charAt(i) != " " || c > 0) {
    res += fld.charAt(i);
    if (fld.charAt(i) != " ") c = res.length;
return res.substr(0,c);

All you need to do is to substitute stp(d) into your validation routine (where d is the name of the field you want to validate) and the field will be validated with leading and trailing blanks removed.

For example to validate that your visitor has entered something (other than blanks) into a mandatory field use:

if (stp(d) == '') alert('d is mandatory');

In this instance the alert message will be displayed if the field is either empty or contains only blanks.

To demonstrate exactly what the above function returns for any given input the button below will display the data you enter into the form field immediately preceded and followed by asterisks (eg. if you enter ' ab c   ' then '*ab c*' will be the result displayed). The button calls alert('*'+stp(d)+'*') to produce the result shown.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow