User input plays a big role on webpages. It acts as an interface between users and the server. Handling user inputs is important as we need to ensure what data can be sent to the server and we cannot expect what the user will send. One of the most common things need to be checked is the input strings.
This time, we take the start and trailing space in text input as an example. Users, mostly casual ones, sometimes input strings with these whitespaces in the input boxes without caring. It does'nt look much difference in a glance. However, in the server side point of view, these start and trailing space does make a lot difference. For example, for a query request and database update request, these spaces can lead to failure of potential hits in the search and failure in finding the existing database entry. So, removing these starting and trailing space is a very common practice. It can be done on the client side when user submit the data.
var startpatt = /^\s/;
var endpatt = /\s$/;
while(str.search(startpatt) == 0)
str = str.substring(1, str.length);
while(str.search(endpatt) == str.length-1)
str = str.substring(0, str.length-1);
The function trim() accept a string object and remove any starting and trailing whitespaces (spaces,tabs and newlines) and return the trimmed string. You can use this function to trim form inputs to ensure valid data to be sent.
The following function uses the trim() function and trim all text input of a form
for (var i = 0; i<form.elements.length; i++)
if(form.elements[i].value != '' && form.elements[i].type == 'text' )
form.elements[i].value = trim(form.elements[i].value);
And you can trigger the call with the onSubmit event in your form declaration.
<form method="POST" action="test.do" onsubmit="return submittrim(this);">