I am using below code snippet to validate my input string with: only capital letters, numbers and two special characters (those are & and Ñ) & without any space between.
var validpattern = new RegExp('[^A-Z0-9\d&Ñ]');
if (enteredID.match(validpattern))
isvalidChars = true;
else
isvalidChars = false;
Test 1: "XAXX0101%&&$#" should fail i.e isvalidChars = false; (as it contains invalid characters like %$#.
Test 2: "XAXX0101&Ñ3Ñ&" should pass.
Test 3: "XA 87B" should fail as it contains space in between
The above code is not working, Can any one help me rectifying the above regex.
This is happening because you have a negation(
^) inside the character class.What you want is:
^[A-Z0-9&Ñ]+$or^[A-Z\d&Ñ]+$Changes made:
[0-9]is same as\d. So useeither of them, not both, although it’s not incorrect to use both, it’s redundant.
^) and endanchor(
$) to match the entirestring not part of it.
+, as thecharacter class matches a single
character.