Search code examples
regexgmailpcre

Validate Gmail username using regex


I'm trying validate Gmail username by using their self rule on create account page.

There are the rules:

  1. First and last character of username must be an ascii letter (a-z) or number (0-9)
  2. Username must be between 6 and 30 characters long
  3. Only letters (a-z), numbers (0-9), and periods (.) are allowed
  4. Username cannot contain consecutive periods (.)

Expecting results:

.carlos.so@gmail.com - invalid
carlos.so.@gmail.com - invalid
carlos..so@gmail.com - invalid
carlos_so@gmail.com - invalid
carlos.so@gmail.com - valid

Already tried the pattern above but without success: (?!\.)[a-zA-Z_.]{6,30}(?!.*\.)


Solution

  • You could use:

    ^[a-zA-Z0-9](?=[a-zA-Z0-9.]{5,29}@)[a-zA-Z0-9]*(?:\.[a-zA-Z0-9]+)*@gmail\.com$
    
    • ^ Start of string
    • [a-zA-Z0-9] Match a single char a-zA-Z0-9
    • (?=[a-zA-Z0-9.]{5,29}@) Assert 5-29 allowed chars to the right followed by @
    • [a-zA-Z0-9]* Match optional chars a-zA-Z0-9
    • (?:\.[a-zA-Z0-9]+)* Optionally repeat matching . and 1+ allowed chars
    • @gmail\.com Match @gmail.com
    • $ End of string

    See a regex101 demo.