I disagree with rolfl's assertion that, "There is no practical way to validate an e-mail address by regex alone."
He is correct—as illustrated by the somewhat infamous SO answer he linked to—that it's impractical to validate any RFC-5322-compliant email addresses because, to quote the HTML5 spec:
RFC-5322 … defines a syntax for e-mail addresses that is simultaneously too strict (before the '@' character), too vague (after the '@' character), and too lax (allowing comments, whitespace characters, and quoted strings in manners unfamiliar to most users) to be of practical use here.
...not to mention that there are now literally thousands of TLDs.
But it's absolutely practical to come up with a very good compromise, which is exactly what the writers of the HTML5 spec did. To that end, the spec provides this PCRE:
This regular expression will yield false positives (rejections) for technically valid email addresses, including ones with spaces and comments (yes, there is a syntax for putting comments in an email address), but practically all email addresses in use in the real world will pass.
As rolfl suggests, the only perfect way to validate an email address is to send an email to it and see if it's received—not all syntactically valid email addresses actually exist, after all—but that doesn't mean we can't use a pretty good validation to give the user useful feedback in the client, and for that we can look to the very smart people who did the work for us when they wrote the HTML5 spec.
As to your second question:
Also is there a difference between this method and just setting the
type="email" in the HTML form?
type="email" makes the browser do the validation for you. That's obvious, I know, but it has a number of implications, some good and some not-necessarily-good. Among them:
- The browser might not do it. It might not support automatic validations, or the user might have disabled it. This limitation could be overcome with a polyfill, however.
- In browsers that support it, it just works, and you don't have to write any code, which is pretty nice.
- Currently there's no widely-supported way to customize the way browsers show HTML5 validation errors, so you can't control how it'll look to the user.
I'm sure there are others, but you get the idea.
My personal recommendation is that unless you have a good reason not to, use
type="email" along with a polyfill (if you have users with older browsers). Very smart people wrote the HTML5 spec, and very smart people wrote the browsers that implement it. Unless you know something that they don't, use the solutions they've already built.