tags:

views:

41

answers:

4

Hi, 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.

+1  A: 

if you want valid patterns, then you should remove the ^ in the character range.

[A-Z0-9\d&Ñ]

ghostdog74
+7  A: 

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 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.
codaddict
upvoted due to ^ and $ which applies regex to entire string.
skyfoot
Thanks, this is working as expected :-).
Biki
Thanks for the explanation, but let me know which part of the regex is responsible for checking the spaces?
Biki
@Biki: We are **allowing only** upper case letters, digits and the two special char. So this automatically does not allow any **other** characters like the space.
codaddict
Ya, Very true. Using jquery we could achieve the same in one line: $('#txtFederalTaxId').alphanumeric({ allow: "
Biki
+3  A: 
^[A-Z\d&Ñ]+$

0-9 not required.

N 1.1
+1 for the simpler form.
Ikaso
A: 

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.

Biki