2

I don't know much regex and when it comes to username it becomes a little tricky, so I request from my fellow programmers to help me validate a username with respect to certain conditions.

  1. Username can only contain letters, numbers, periods and underscores.
  2. Username can start and end with underscores but never with periods. (for security reasons)
  3. Username length should be between 4 and 20 characters.
  4. Spaces are not allowed

Examples of valid and invalid usernames:

josh valid

.josh_ invalid

_josh. invalid

_josh_123.brad valid

josh brad invalid

I have already searched and the answer I find didn't quite help. This is my regex for now:

RegExp('^(?=[A-Za-z0-9._]{4,20}$)[^_.].*[^_.]');

Thanks in advance

1 Answer 1

3

This can be achieved without any lookahead:

/^\w[\w.]{2,18}\w$/

If you want to use RegExp then use:

var re = new RegExp("^\\w[\\w.]{2,18}\\w$");

RegEx Demo

Pattern Details:

  • \w: is a shortcut for [a-zA-Z0-9_]
  • ^: Start
  • \w: Match a word character
  • [\w.]{2,18}: Match 2 to 18 counts of word or dot characters thus making total length between 4 to 20
  • \w: Match a word character
  • $: End
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks man, that worked like a charm. Unfortunately, I need more reps to upvote your answer. Anyway, thanks