sasori
sasori

Reputation: 5463

enforce a no spacebar when filling up input form

I have an input form for username, but I wish to not let the user to add space OR press spacebar when adding a username, how to do that in jquery, I mean, how to add such validation in my current code ?

 if(document.getElementById("cvusername")!== null && (cvusername == "" || cvusername.length < 5 || cvusername.length > 30)){
    alert("-username is required\n-should not be less than 5 characters\n and not greater than 30 characters");
    return false;
 }

Upvotes: 1

Views: 1083

Answers (3)

thecodeparadox
thecodeparadox

Reputation: 87073

<input type="text" id="nospace" />

$('#nospace').keypress(function(event) {
    if (event.which == 32) {
        alert('No space');
        return false;
    }

     // this is for PASTE (ctrl + v)
  if(event.ctrlKey && event.which == 86) {
    alert('no space allowed');
    $(this).val($(this).val().replace(' ',''));
  }

});

Upvotes: 2

alex
alex

Reputation: 490617

I have an input form for username, but I wish to not let the user to add space OR press spacebar when adding a username, how to do that in jQuery?

On the keyup event, you could strip all whitespace characters from the input element.

$('input:text').keyup(function() {
    $(this).val(function(i, value) {
       return value.replace(/\s/, '');
    });
});

jsFiddle.

...how to add such validation in my current code ?

To validate it again on submit, just use $('input:text').val().search(/\s/) === -1. That will return true if valid.

jsFiddle.

As the commenters suggested, you may want to also bind to the paste event and similar.

Make sure you confirm the whitespace is missing on the server side as well.

Upvotes: 4

hoppa
hoppa

Reputation: 3041

Check if there is a space character in the username:

if(document.getElementById("cvusername")!== null && 
  (cvusername == "" || 
   cvusername.length < 5 || 
   cvusername.length > 30 ||
   cvusername.indexOf(' ') != -1)){

    alert("-username is required\n-should not be less than 5 characters\n and not greater than 30 characters. It may also not contain spaces");
    return false;
}

Upvotes: 3

Related Questions