I am trying to validate a username field like this:
- 6 alphabets mandatory
- Might contain any number of numericals
- Might contain any number of underscores
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.
CodePudding user response:
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.
CodePudding user response:
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'))
CodePudding user response:
You can do:
^\w*(?:[A-Za-z]\w*){6,}$