简体   繁体   中英

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 [~!#$].

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.

However input such as this works: 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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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