Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 584
Luke Shaheen Avatar asked Oct 31 '11 19:10

Luke Shaheen


2 Answers

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.');
like image 125
Donut Avatar answered Nov 12 '22 04:11

Donut


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.

like image 27
Ray Toal Avatar answered Nov 12 '22 04:11

Ray Toal