Your regex fails because of the first lookahead pattern (?=^[a-z]+\d{2,})
. The string "astr1on11aut" starts with lowercase letters:
astr1on11aut
^^^^
This matches ^[a-z]+
. However, the next part of the pattern demands two or more digits with \d{2,}
, however the string only has one at that place:
astr1on11aut
^^
||
digit -+|
+ --- not a digit
This causes the first lookahead pattern to fail.
You can express the validation rules more cleanly with three lookaheads:
- "greater than 5 characters long:
(?=.{5,})
- "do not begin with numbers":
^(?!\d)
- "and have two consecutive digits":
(?=.*\d{2})
If we put them all together we get /(?=.{5,})(?!^\d)(?=.*\d{2})/
const regex = /^(?=.{5,})(?!\d)(?=.*\d{2})/;
test("abc");
test("123");
test("123abc");
test("abc123");
test("astr1on11aut");
test("., ;_'@=-%");
test("., ;_'@123=-%");
function test(string) {
console.log(`${string} : ${regex.test(string)}`);
}
Note that this regex doesn't require letters. Strictly following the requirements, the only thing explicitly asked for is digits. Since the type of any other input is not specified, it's left to be anything (using .
). It's best not to make too many assumptions when writing a regular expression or you might block legitimate input.