Search code examples
c#regexemail-validation

Regular Expression for given scenario


I already have an email address regular expression FROM RFC 2822 FORMAT

[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?

but want to modify it to include the following some new conditions:

  1. at least one full stop
  2. at least one @ character
  3. no consecutive full stops
  4. must not start/end with special characters i.e. should only start/end with [0-9a-zA-Z]
  5. should still follow RFC specification for regular expression rules.

Currently the above one allows the email to start with special characters. Also it is allowing two consecutive full stops (except for domain name which is fine, so [email protected] fails and its correct).

Thanks.


Solution

  • ^[a-zA-Z0-9]+(?:\.?[\w!#$%&'*+/=?^`{|}~\-]+)*@[a-zA-Z0-9](?:\.?[\w\-]+)+\.[A-Za-z0-9]+$
    

    No .. and at least 1 . and 1 @.
    Also starts/ends with letters/numbers.

    The ^ (start) and $ (end) were just added to match a whole string, not just a substring. But you could replace those by a word boundary \b.

    An alternative where the special characters aren't hardcoded:

    ^(?!.*[.]{2})[a-zA-Z0-9][^@\s]*?@[a-zA-Z0-9][^@\s]*?\.[A-Za-z0-9]+$