Following is the regex that I tried to validate against the below mentioned criteria, but in some cases its failing. Let me know what I am doing wrong here.
Regex-
/[a-z]|\d|\_{4, 16}$/.test(username)
Criteria -
Allowed characters are:
Code
function validateUsr(username) { res = /[az]|\d|\_{4, 16}$/.test(username) return res } console.log(validateUsr('asddsa')); // Correct Output - true console.log(validateUsr('a')); // Correct Output - false console.log(validateUsr('Hass')); // Correct Output - false console.log(validateUsr('Hasd_12assssssasasasasasaasasasasas')); // Correct Output - false console.log(validateUsr('')); // Correct Output - false console.log(validateUsr('____')); // Correct Output - true console.log(validateUsr('012')); // Correct Output - false console.log(validateUsr('p1pp1')); // Correct Output - true console.log(validateUsr('asd43 34')); // Correct Output - false console.log(validateUsr('asd43_34')); // Correct Output - true
You may join the patterns to a single character class and apply the limiting quantifier to the class, not just to the _
pattern. Note the space is meaningful inside a pattern, and {4, 16}
matches a {4, 16}
string, it is not parsed as a quantifier.
You may use
var regex = /^[az\d_]{4,16}$/; function validateUsr(username) { return regex.test(username) } console.log(validateUsr('asddsa')); // Correct Output - true console.log(validateUsr('a')); // Correct Output - false console.log(validateUsr('Hass')); // Correct Output - false console.log(validateUsr('Hasd_12assssssasasasasasaasasasasas')); // Correct Output - false console.log(validateUsr('')); // Correct Output - false console.log(validateUsr('____')); // Correct Output - true console.log(validateUsr('012')); // Correct Output - false console.log(validateUsr('p1pp1')); // Correct Output - true console.log(validateUsr('asd43 34')); // Correct Output - false console.log(validateUsr('asd43_34')); // Correct Output - true
The ^[az\d_]{4,16}$
- see its demo - pattern means:
^
- start of string [
- start of a character class:
az
- ASCII lowercase letters \d
- ASCII digit _
- an underscore ]{4,16}
- end of the class, repeat four through sixteen times $
- end of string.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.