Jump to content

Prevent a "Space" from being first characted typed in a text field


galvin

Recommended Posts

Anyone know how to add some javascript to prevent a user from typing a "space" as the FIRST character (in a simple text field)?  In other words, if the user accidentally hits the space key before typing anything else, it will be essentially be ignored. 

(I know there are ways to strip a leading space after the text is submitted, but I need it to not even get to that point for reasons I won't bore you with).

Any help/ideas would be greatly appreciated.

-Greg

Link to comment
Share on other sites

Or you could validate on the 'onblur' event. I'd probably just use one of the many custom trim functions/prototypes available online, something like this (found here):

 

<script type="text/javascript">
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
</script>

 

<input type="text" name="..." onblur="this.value = this.value.trim();" />

 

You may wish to switch to the 'onkeyup' event if it needs to be validated after every character is input.

 

There's load of other ways you could do it as well...

Link to comment
Share on other sites

Anyone know how to add some javascript to prevent a user from typing a "space" as the FIRST character (in a simple text field)?  In other words, if the user accidentally hits the space key before typing anything else, it will be essentially be ignored. 

(I know there are ways to strip a leading space after the text is submitted, but I need it to not even get to that point for reasons I won't bore you with).

Any help/ideas would be greatly appreciated.

-Greg

 

I'd like to hear these long and boring reasons that somehow justify client-side validation over server-side validation.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.