简体   繁体   中英

Javascript RegEx to return if string contains characters that are NOT in the RegEx

I have a user created string. I am only allowing the characters AZ, az, 0-9, -, and _

Using JavaScript, how can I test to see if the string contains characters that are NOT these? If the string contains characters that are not these, I want to alert the user that it is not allowed.

What Javascript methods and RegEx patterns can I use to match this?

You need to use a negated character class. Use the following pattern along with the match function :

[^A-Za-z0-9\-_]

Example:

var notValid = 'This text should not be valid?';

if (notValid.match(/[^A-Za-z0-9\-_]/))
   alert('The text you entered is not valid.');

This one is straightforward:

if (/[^\w\-]/.test(string)) {
    alert("Unwanted character in input");
}

The idea is if the input contains even ONE disallowed character, you alert.

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