Regex to not allow particular special characters at start or end of email name in email address

Viewed 85

I have the following regex condition for email address.

var value = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9]+\.[a-zA-Z{2,}$/

But I dont want the name to start or end with period(.) or underscore(_) or hyphen (-) and this given special characters should include in middle only.

for eg :

            _name.name_@email.com Invalid
             -name.name-@email.com Invalid
              name.@email.com Invalid
              name_@email.com Invalid
              name-@email.com Invalid
              .name@email.com Invalid
              _name@email.com Invalid
              -name@email.com Invalid
              name.name@email.com Valid
              name_name@email.com Valid
              name-name@email.com Valid

I am trying to figure out the solution and learn in the process.

1 Answers

You can use

var value = /^[a-zA-Z0-9]+(?:[._-][a-zA-Z0-9]+)*@[a-zA-Z0-9]+\.[a-zA-Z]{2,}$/

Details:

  • ^ - start of string
  • [a-zA-Z0-9]+ - one or more letters/digits
  • (?:[._-][a-zA-Z0-9]+)* - zero or more occurrences of ./_/- and then one or more letters/digits
  • @ - a @ char
  • [a-zA-Z0-9]+ - one or more letters/digits
  • \. - a dot
  • [a-zA-Z]{2,} - two or more letters
  • $ - end of string.

See the regex demo.

Related