JavaScript Tip: Trim Strings with YUI
Any programmer worth his salt knows that when you perform even the most minimal validation on a set of input textboxes for a form, that you need to wrap some kind of trim function around the string. So many times, I see developers write the following as a validation rule:
if(this=="")
alert('Please provide a value for "this"');
}
Clearly, all the user would have to do is provide a value with either a space or line break to make the value valid. The whole point of checking the value to ensure it is not empty is to ensure that the user did not provide only non-characters as well!!! The way to accomplish this type of validation would be simply to use the common programming function known as trim. The basics is that the function will shave off any spaces at the beginning and end of a given string to ensure the string is not padded. In the case of value that has only a space, this would make the string appear as completely empty.
Well for those attempting to accomplish the above in JavaScript will be out of luck unless they write the function themselves. Now, simply searching for "JavaScript trim" provide a plethora of results that will work just fine. However, being a proponent of YUI, I prefer to use the built-in tools and functions it offers if available. Sure enough, simply searching for YUI Trim in Google yielded that the function does indeed exist and, of course, is quite easy to use:
if(YAHOO.lang.trim(this)=="")
alert('Please provide a value for "this");
}
</code>



There are no comments for this entry.
[Add Comment]