I'm trying to write a Regex What I need is:
- To start only with: A-z (Alphabetic)
- Min. Length: 5
- Max. Length: 10
- The rest can be A-z0-9(Alphanumeric) but contain at least one number
What I have: ^[A-z][A-z0-9]{5,10}$
I'm trying to write a Regex What I need is:
What I have: ^[A-z][A-z0-9]{5,10}$
You can use
/^(?=.{5,10}$)[a-z][a-z]*\d[a-z\d]*$/i
See the regex demo
Details:
^
- start of string(?=.{5,10}$)
- the string should contain 5 to 10 any chars other than line break chars (this will be restricted by the consuming pattern later) up to the end of string[a-z]
- the first char must be an ASCII letter (i
modifier makes the pattern case insensitive) [a-z]*
- 0+ ASCII letters\d
- 1 digit[a-z\d]*
- 0+ ASCII letters of digits$
- end of string.var ss = [ "ABCABCABC1","ABCA1BCAB","A1BCABCA","A1BCAB","A1BCA","A1BC","1BCABCABC1","ABCABC","ABCABCABCD"]; // Test strings
var rx = /^(?=.{5,10}$)[a-z][a-z]*\d[a-z\d]*$/i; // Build the regex dynamically
document.body.innerHTML += "Pattern: <b>" + rx.source
+ "</b><br/>"; // Display resulting pattern
for (var s = 0; s < ss.length; s++) { // Demo
document.body.innerHTML += "Testing \"<i>" + ss[s] + "</i>\"... ";
document.body.innerHTML += "Matched: <b>" + rx.test(ss[s]) + "</b><br/>";
}
var pattern = /^[a-z]{1}\w{4,9}$/i;
/* PATTERN
^ : Start of line
[a-z]{1} : One symbol between a and z
\w{4,9} : 4 to 9 symbols of any alphanumeric type
$ : End of line
/i : Case-insensitive
*/
var tests = [
"1abcdefghijklmn", //false
"abcdefghijklmndfvdfvfdv", //false
"1abcde", //false
"abcd1", //true
];
for (var i = 0; i < tests.length; i++) {
console.log(
tests[i],
pattern.test(tests[i])
)
}