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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With