Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading