7

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?

2 Answers 2

15

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.');
Sign up to request clarification or add additional context in comments.

2 Comments

Thats the pattern, but what Javascript method can I use? Thank you
6

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.

1 Comment

Just to clarify for people like me: /[^\w\-]/ - this cotains the whitelist, meaning the list of allowed characters. To add something to it, append it after the dash, for example like so: /[^\w\-äöÄÖ]/.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.