Mahi
Mahi

Reputation: 593

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

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 example:

[email protected] Invalid
[email protected] Invalid
[email protected] Invalid
[email protected] Invalid
[email protected] Invalid
[email protected] Invalid
[email protected] Invalid
[email protected] Invalid
[email protected] Valid
[email protected] Valid
[email protected] Valid

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

Upvotes: 1

Views: 2695

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626952

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.

Upvotes: 2

Related Questions