javascriptregexvalidation

Regex for telegram-like username


I`m building messaging app and I need regular expression to validate username while signing a new user up. Username must be at least 5-characters long(no less than 3 characters of that length must be letters), no spaces, and may consist only of a-z, 0–9, and underscores.

const valid = new RegExp(...);

const username_a = "john_doe";
const username_b = "johndoe";
const username_c = "John Doe";
const username_d = "john.doe";
const username_e = "john";

valid.test(username_a) = true;
valid.test(username_b) = true;
valid.test(username_c) = false;
valid.test(username_d) = false;
valid.test(username_e) = false;

I'm not familiar with regex building, so pls help!


Solution

  • As suggested in the comment by Pushpesh:

    const valid = /^(?=(?:[0-9_]*[a-z]){3})[a-z0-9_]{5,}$/;
    
    const names = 'john_doe,johndoe,j2e2p2,John Doe,john.doe,johh,joh2_23,jo2e_234,jo23_22'.split(',');
    
    for(const name of names){
      console.log(name, valid.test(name));
    }