Disabling spaces/spacebar in a form textfield

Say I have a textbox in a form that I do not want the user to have the ability to put any spaces. This example is for someone’s name converting to a short url so no matter what, their name is like JohnDoe and during the typing of it, the user cannot put a space between their name. Is this an HTML or Javascript thing to pretty much disable spacebar just for that field?

It’s a serverside validation/sanitization thing.

Have you considered all the other characters which may not be allowed or may have special meaning in a url? You might consider making a whitelist of allowed characters.

After you have completed the serverside code, you can optionally add some javascript to give immediate feedback in case the user enters an invalid character.

isnt there a jQuery function or addon?

you could use a function triggered onKeyUp to replace the spaces in the textbox like onkeyup=“strip_spaces();”

very roughly in the function:
textbox_variable.replace(" ", “”);

I’m sure I have used it before somewhere…

replace(/\s/g, “”);

would work better as it will remove all the whitespace characters and not just those entered using the spacebar.

Did you want me to do that in javascript or php? I’m basically using this code from the jquery_twitter script and the jquery validate:

<label for="username">Personal URL:<input type="text" id="username" name="username" onkeyup="ucheck.updateUrl(this.value)" style="width:200px; margin-left:36px;" validate="required:true">

Whatever you do for form validation has to be done in the PHP. You then duplicate as much of that as is useful in JavaScript for those who have it enabled so as to avoid the need to submit the form in order to find the errors when possible.

nice! :wink:

Incase anyone else needs this:


$('input.nospace').keydown(function(e) {
    if (e.keyCode == 32) {
        return false;
    }
});

How would I implement this on my site? Should I just put the following code in wrapped in script tags in my header? Thanks in advance!!!