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.
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.
Share Improve this question edited Dec 25, 2010 at 8:34 codaddict 455k83 gold badges499 silver badges536 bronze badges asked Oct 20, 2010 at 11:29 BikiBiki 2,5888 gold badges39 silver badges53 bronze badges 2- 3 What about your previous question? – Gumbo Commented Oct 20, 2010 at 11:31
- 1 Maybe you should remove the negation ^. – Ikaso Commented Oct 20, 2010 at 11:33
4 Answers
Reset to default 11This 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 use either of them, not both, although it's not incorrect to use both, it's redundant.- Added start anchor (
^
) and end anchor($
) to match the entire string not part of it. - Added a quantifier
+
, as the character class matches a single character.
^[A-Z\d&Ñ]+$
0-9
not required.
if you want valid patterns, then you should remove the ^
in the character range.
[A-Z0-9\d&Ñ]
Using jquery we could achieve the same in one line:
$('#txtId').alphanumeric({ allow: " &Ñ" });
Using regex (as pointed by codaddict) we can achieve the same by
var validpattern = new RegExp('^[A-Z0-9&Ñ]+$');
Thanks everyone for the precious response added.