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 user开发者_开发百科name, 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;
}
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.
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;
}
<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(' ',''));
}
});
精彩评论