0

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:

  • lowercase letters
  • Numbers
  • Underscore
  • Length should be between 4 and 16 characters (both included).

Code

function validateUsr(username) {
  res =  /[a-z]|\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

1 Answer 1

3

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 = /^[a-z\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 ^[a-z\d_]{4,16}$ - see its demo - pattern means:

  • ^ - start of string
  • [ - start of a character class:
    • a-z - ASCII lowercase letters
    • \d - ASCII digit
    • _ - an underscore
  • ]{4,16} - end of the class, repeat four through sixteen times
  • $ - end of string.
Sign up to request clarification or add additional context in comments.

2 Comments

What is the meaning of ^ in /^[a-z\d_]{4,16}$/ ?
@Nesh I added details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.