Reputation: 10575
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}$/;
Upvotes: 3
Views: 235
Reputation: 156464
[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.
Upvotes: 3
Reputation: 34395
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}$
).
Upvotes: 11
Reputation: 26930
All possible combinations 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
}
Upvotes: 4