开发者

How to restrict single word (that itselft having only string not number) while entering value in inputbox

开发者 https://www.devze.com 2023-03-20 04:42 出处:网络
Im using this code to re开发者_高级运维strict the user to not enter special characters $(\"input\").keyup(function(){

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" />
0

精彩评论

暂无评论...
验证码 换一张
取 消