Im using this code to re开发者_高级运维strict the user to not enter special characters
$("input").keyup(function(){
var text=$(this).val();
$(this).val(text.replace(/[^\w\d\s]/,""));
})
I want to restrict the user to enter only one word without space and also having no numbers and special characters. like this
myword #valid
myword2 #invalid
myword secondword #invalid
$(this).val(text.replace(/[^A-Za-z]/g,''));
Test it here »
here's a jQuery plugin that will prevent typing keys that are not in the specified regex. It also works if you paste something, but that works with replace.
$("body").delegate("[keyfilter]", "keypress", function(event) {
var elem = $(this), filter = elem.attr('keyfilter');
if (event.charCode === 0) {
return;
}
try {
if (!String.fromCharCode(event.charCode).match(new RegExp("[" + filter + "]"))) {
event.preventDefault();
event.stopImmediatePropagation();
}
} catch(e) {}
}).delegate("[keyfilter]", "paste", function(event) {
var elem = $(this), filter = elem.attr('keyfilter');
setTimeout(function() { elem.val(elem.val().match(new RegExp("[" + filter + "]"))[0]) }, 50);
});
the way to use it:
<input type="text" keyfilter="A-Za-z" />
精彩评论