最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regex to check only capital letters, two special characters (& and Ñ) & without any space

programmeradmin4浏览0评论

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
Add a ment  | 

4 Answers 4

Reset to default 11

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.
^[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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论