简体   繁体   English

如何使用正则表达式和jQuery匹配字符集中不存在的所有内容?

[英]How can I match everything not in a character set with regex and jQuery?

I'm trying to exclude everything except [az] [AZ] [0-9] and [~!#$]. 我正在尝试排除 [az] [AZ] [0-9]和[〜!#$]以外的所有内容。

if( $("#name").val().test(/[^a-zA-Z0-9~!#$]/)) {
    alert("Disallowed character used.");
    return false;
}

I thought test would return true if it finds a match and that because I included the caret symbol it should match everything that is not in my expression. 我认为test如果找到匹配项将返回true,这是因为我包括了插入符号,它应该与表达式中不存在的所有内容匹配。

However input such as this works: jAcK%%$21#x 但是,这样的输入有效:jAcK %% $ 21#x

When it shouldn't work because it has symbols I'm trying to disallow. 当它因为有符号而无法正常工作时,我正尝试禁止这样做。

Where have I gone wrong? 我哪里出问题了?

Thanks 谢谢

Use match instead of test , since test is function of RegExp instead of String 使用match代替test ,因为test是RegExp函数而不是String

var hasBadInput = !!"jAcK%%$21#x".match(/[^a-zA-Z0-9~!#$]/) //true

Or reverse the position 或反转位置

(/[^a-zA-Z0-9~!#$]/).test("jAcK%%$21#x") //returns true

Regexp.prototype.test() should be called on the regex. Regexp.prototype.test()应该在正则表达式上调用。

 var $name = $("#name"); $name.on("keyup", function(e) { if(/[^a-zA-Z0-9~!#$]/.test($name.val())) { console.log("Nope"); return false; } else { console.log("Good"); } }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="name" > 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM