使用正则表达式在字符串中查找不匹配字符

时间:2015-03-17 10:58:40

标签: javascript regex validation

当文本输入/粘贴文本时,我必须找到并向用户显示文本区域中除键盘字符以外的任何特殊字符,下面我解释了我要做的事情!请尽快帮助我?

if ($(txtMessage).val().trim() != "") {
         var pattern = "^[a-zA-Z0-9~`!@#$%^&*()_+-={}|:;<>,.?\/']+$";
         for(var i=0;i<$(txtMessage).val().length;i++){
             var subStr=$(txtMessage).val().substring(0, i);
             if(!subStr.match(pattern)){
                 $('#customDailogBox')
                    .text(
                            "You have entered or paste "+subStr.substring(i, i)+"input  characters are not supported characters!!!..");
             }
         }

1 个答案:

答案 0 :(得分:2)

更改循环条件和子字符串函数

 for(var i=1;i=<$(txtMessage).val().length;i++){
         var subStr=$(txtMessage).val().substr(i,1);
         if(!subStr.match(pattern)){
             $('#customDailogBox').text("You have entered or paste "+subStr.substring(i, i)+"input  characters are not supported characters!!!..");
         }
}

或者您也可以使用正则表达式匹配整个字符串

var unmatched_characters = $(txtMessage).val().match(/[^a-zA-Z0-9~`!@#$%^&*()_+-={}|:;<>,.?\/']/g);
if (unmatched_characters.length>0){
     $('#customDailogBox').text("You have entered or paste some characters that are not supported !!!..");
}