Reputation: 1524
I am trying to validate a username field like this:
For example: abcdef, abc9def, _testaa, __test_aa_, hello_h_9, _9helloa, 9a8v6f_aaa All these should match, that is, the number of alphabets should be more than n numbers (here 6) in the whole string, and _ and numerics can be present anywhere.
I have this regex: [\d\_]*[a-zA-Z]{6,}[\d\_]*
It matches strings like: _965hellof
But doesn't match strings like: ede_96hek
I also have tried this regex: ^(?:_?)(?:[a-z0-9]?)[a-z]{6,}(?:_?)(?:[a-z0-9])*$
Even this fails to match.
Upvotes: 3
Views: 85
Reputation: 106883
You can do:
^\w*(?:[A-Za-z]\w*){6,}$
Demo: https://regex101.com/r/yoGr82/1
Upvotes: 2
Reputation: 17394
One solution is splitting the str
and on each character checking if it's an alphabet with .filter(v => isNaN(v) && v !== '_')
and then get the length
to check if it's more than 6 alphabets.
const checkValidation = (str) => {
return /[\d\_a-z]/gi.test(str) && str.split('').filter(v => isNaN(v) && v !== '_').length >= 6
}
console.log(checkValidation('something_123'))
console.log(checkValidation('12somtg1'))
console.log(checkValidation('123some12tg'))
console.log(checkValidation('123some12_'))
console.log(checkValidation('_965hellof'))
console.log(checkValidation('ede_96hek'))
Upvotes: 2
Reputation: 2580
You need to use a lookahead like this:
/^(?=[^A-Za-z]*([A-Za-z][^A-Za-z]*){6}$)\w+$/
This is in two parts, the long part verifies there are exactly 6 alphabetic characters present without moving the scanners cursor position. Then the \w+ says all the characters must be alphanumeric or underscore. The ^ & $ ensure the entire string conforms.
Upvotes: 2