James Glass
James Glass

Reputation: 4300

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 A-Z, a-z, 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?

Upvotes: 7

Views: 22859

Answers (2)

Donut
Donut

Reputation: 112815

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.');

Upvotes: 15

Ray Toal
Ray Toal

Reputation: 88378

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.

Upvotes: 6

Related Questions