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

jquery - How do I write javascript Regex in such way it accepts 6 Characters - Stack Overflow

programmeradmin2浏览0评论

Javascript regex to validate that it contains 6 characters and in which one character (1) should be a number.

var pwdregex  =/^[A-Za-z1-9]{6}$/;

Javascript regex to validate that it contains 6 characters and in which one character (1) should be a number.

var pwdregex  =/^[A-Za-z1-9]{6}$/;
Share Improve this question asked Oct 13, 2011 at 21:21 SomeoneSomeone 10.6k23 gold badges71 silver badges101 bronze badges 5
  • Whats the problem with your current RegEx? Do you want that the first character of the sting is a digt? – styrr Commented Oct 13, 2011 at 21:24
  • 1 Do you want it to be exactly 6 chars long (no longer, no shorter)? Do you want there to be exactly one numeric character (no more, no less) and the rest alpha? – jfriend00 Commented Oct 13, 2011 at 21:24
  • 4 Why do you exclude the number "zero"? – Aurelio De Rosa Commented Oct 13, 2011 at 21:25
  • 1 Why do you need to do it all in a regex? Why not check that the length of the string is six characters, and do a regex to ensure that there is one digit? – CanSpice Commented Oct 13, 2011 at 21:26
  • @jfriend:yes i want exactly 6 characters long in which there should be 1 character as number – Someone Commented Oct 13, 2011 at 21:28
Add a ment  | 

3 Answers 3

Reset to default 11

This will guarantee exactly one number (i.e. a non-zero decimal digit):

var pwdregex = /^(?=.{6}$)[A-Za-z]*[1-9][A-Za-z]*$/;

And this will guarantee one or more consecutive number:

var pwdregex = /^(?=.{6}$)[A-Za-z]*[1-9]+[A-Za-z]*$/;

And this will guarantee one or more not-necessarily-consecutive number:

var pwdregex = /^(?=.{6}$)[A-Za-z]*(?:[1-9][A-Za-z]*)+$/;

All of the above expressions require exactly six characters total. If the requirement is six or more characters, change the {6} to {6,} (or remove the $ from {6}$).

All possible binations of 1 digit and alphanumeric chars with a length of 6.

if (subject.match(/^[a-z]{0,5}\d[a-z]{0,5}$/i) && subject.length == 6) {
    // Successful match
} else {
    // Match attempt failed
}

[Edit] Fixed obvious bug...

If you are ok with using a function instead of a regex you can do this:

var sixAlphaOneDigit = function(s) {
  return !!((s.length==6) && s.replace(/\d/,'').match(/^[A-Za-z]{5}$/));
};

sixAlphaOneDigit('1ABCDE'); // => true
sixAlphaOneDigit('ABC1DE'); // => true
sixAlphaOneDigit('ABCDE1'); // => true
sixAlphaOneDigit('ABCDE'); // => false
sixAlphaOneDigit('ABCDEF'); // => false
sixAlphaOneDigit('ABCDEFG'); // => false

If you want to do it strictly in a regex then you could build a terribly long pattern which enumerates all possibilities of the position of the digit and the surrounding (or leading, or following) characters.

发布评论

评论列表(0)

  1. 暂无评论