简体   繁体   中英

Regex to validate a username in react native

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM