Arjun
Arjun

Reputation: 21

JS regex to match a username with specific special characters and no consecutive spaces

I am pretty new to this reg ex world. Struck up with small task regarding Regex. Before posting new question I have gone thru some answers which am able to understand but couldnt crack the solution for my problem Appreciate your help on this.

My Scenario is:

Validating the Username base on below criteria

1- First character has to be a-zA-Z0-9_@ (either of two special characters(_@) or alphanumeric)

2 - The rest can be any letters, any numbers and -@_ (either of three special characters and alphanumeric).

3 - BUT no consecutive spaces between words.

4- Max size should be 30 characters

my username might contain multiple words seperated by single space..for the first word only _@ alphanumeric are allowed and for the second word onwards it can contain _-@aphanumeric

Need to ignore the Trailing spaces at the end of the username

Examples are: @test, _test, @test123, 123@, test_-@, test -test1, @test -_@test etc...

Appreciate your help on this..

Thanks Arjun

Upvotes: 2

Views: 1041

Answers (2)

user557597
user557597

Reputation:

This might work ^(?=.{1,30}$)(?!.*[ ]{2})[a-zA-Z0-9_@]+(?:[ ][a-zA-Z0-9_@-]+)*$

Note - the check for no consecutive spaces (?! .* [ ]{2} ) is not really
necessary since the regex body only allows a single space between words.
It is left in for posterity, take it out if you want.

Explained

 ^                        # BOS
 (?= .{1,30} $ )          # Min 1 character, max 30
 (?! .* [ ]{2} )          # No consecutive spaces (not really necessary here)
 [a-zA-Z0-9_@]+           # First word only
 (?:                      # Optional other words
      [ ] 
      [a-zA-Z0-9_@-]+ 
 )*
 $                        # EOS

Upvotes: 0

Jan
Jan

Reputation: 43169

Here you go:

^(?!.*[ ]{2,})[\w@][-@\w]{0,29}$

See it working on regex101.com.
Condition 3 is ambigouus though as you're not allowing spaces anyway. \w is a shortcut for [a-zA-Z_], (?!...) is called a neg. lookahead.


Broken down this says:

^             # start of string
(?!.*[ ]{2,}) # neg. lookahead, no consecutive spaces
[\w@]         # condition 1
[-@\w]{0,29}  # condition 2 and 4
$             # end of string

Upvotes: 0

Related Questions