Nesh
Nesh

Reputation: 2541

Regex to validate username in Javascript

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 =  /[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

Upvotes: 0

Views: 511

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

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.

Upvotes: 3

Related Questions