Duke Dougal
Duke Dougal

Reputation: 26326

How to check string against whitelisted characters in JavaScript?

I have a bit of code that transforms user input to ensure the only allowed characters are abcdefghijklmnopqrstuvwxyz-0123456789

https://jsfiddle.net/py4pnr0L/

value = 'GHJHlk;sxa787BVK'
value = value.toLowerCase()
value = value.replace(/[^a-z0-9\-]/gi, '-')
console.log(value)

Returns: ghjhlk-sxa787bvk

How would I go about not transforming, but just testing to find if a given string contains characters outside the permitted range?

All I want to know is true/false for a given input string.

I am using ES2015 so if the cleanest solution is available using ES2015 then that is fine.

Upvotes: 3

Views: 8867

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

You can use RegExp#test() method:

Executes a search for a match between a regular expression and a specified string. Returns true or false.

No /g modifier should be used with this method so that the lastIndex property could not mess the results. See Why RegExp with global flag in Javascript give wrong results? for details.

Your regex /[^a-z0-9-]/i (matches any character that is not in the a-z and A-Z and 0-9 ranges and not -) can be used here. Just take out the /g.

var value = "GHJHlksxa787BVK";
document.body.innerHTML = /[^a-z0-9-]/i.test(value);

The /i is a case insensitive modifier, /[a-z]/i = /[A-Za-z]/.

Upvotes: 0

maioman
maioman

Reputation: 18734

you can use match method , try something like:

value = 'GHJHlksxa787BVK';
 
console.log(!value.match(/[^a-zA-Z0-9\-]/))

Upvotes: 1

Related Questions