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
3 Answers
Reset to default 11This 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.