1
votes

I'm trying to build a regular expression to detect a valid email. I've gone through some articles here on Stack Overflow. I've also read the section 3.4.1 of RFC 2822, which describes the different components of an email address:

addr-spec       =       local-part "@" domain

local-part      =       dot-atom / quoted-string / obs-local-part

domain          =       dot-atom / domain-literal / obs-domain

domain-literal  =       [CFWS] "[" *([FWS] dcontent) [FWS] "]" [CFWS]

dcontent        =       dtext / quoted-pair

dtext           =       NO-WS-CTL /     ; Non white space controls

                        %d33-90 /       ; The rest of the US-ASCII
                        %d94-126        ;  characters not including "[",
                                        ;  "]", or "\"

In simple English, can someone explain the definition above? Does it allow for an email such as info@[192.168.0.1]?

I know that I don't have to re-invent the wheel, and that there are good libraries that I can use to validate an email. I just want to understand how things work under the hood.

1
Why are you building something that already exists? If not for educational purposes, please don't roll your own email validation.F.P

1 Answers

0
votes

In PHP you can use FILTER_VALIDATE_EMAIL. No libs required

<?php
$email = "john.doe@example.com";

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
  echo("$email is a valid email address");
} else {
  echo("$email is not a valid email address");
}
?>