Referencing my comment, you can use either of the following to catch any characters that are not in the list you presented.
a-z
A-Z
0 to 9
!$%&*:;#~@
[^a-zA-Z0-9!$%&*:;#~@]
Click here to see it in action. I did some keyboard smashing and, as you can see, it's grabbing the characters not found in the list.
If you want to present the user with an error surround the regex above with (
regex here)
and if your matches are greater than 0, reject the entry.
As per the generated code on regex101 (in the external link provided), you can test it using the following code.
const regex = /([^a-zA-Z0-9!$%&*:;#~@])/g;
const str = `afdskljfalsfhaljsf jdsalfhajslfjdsf haskjlfjdskfa sdfl;dasj fas kjdfs2345tg!@*%(&)&^%\$@#@!!\$%^&%(\$%\$##@\$@>?"{P}P@#!é45049sgfg~~~\`\`\`j;fad;fadsfafds
{":
fd
:"L'KM"JNH¨MJ'KJ¨HN'GFDMG`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
In the above code, any matches are caught in the last forEach
block and output to the console. You can use an if
statement instead to output an error if matches occurred. Take a look at Check whether a string matches a regex, a post that explains how to test for matches
Use regex.test()
if all you want is a boolean result:
/^([a-z0-9]{5,})$/.test('abc1'); // false
/^([a-z0-9]{5,})$/.test('abc12'); // true
/^([a-z0-9]{5,})$/.test('abc123'); // true
...and you could remove the ()
from your regexp since you've no need
for a capture.