Email validation in Golang
One shall not write from scratch an email syntax validator because it’s an activity that most likely has nothing to do with the domain of the system one is working on.
Moreover, often if/elses and regular expressions tend to be naive approaches to such a problem.
In Go, one shall avoid code such as the one written below because it’s ugly, complex, hard to maintain, and it isn’t even effective at validating perfectly valid email addresses.
1var pattern = regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")
Instead one is provided with the package net/mail, which has a function to parse email addresses based on the RFC 5322, and here is how one can leverage it:
1package main
2
3import (
4 "fmt"
5 "net/mail"
6)
7
8func main() {
9 err := validateEmail("tim.cookapple.com")
10 if err != nil {
11 fmt.Println(err)
12 return
13 }
14}
15
16func validateEmail(address string) error {
17 _, err := mail.ParseAddress(address)
18 if err != nil {
19 return err
20 }
21
22 return nil
23}
> mail: missing '@' or angle-addr
What if one still wants to write an email validator from scratch?
That’s a reasonable question for the sake of learning or any other reason one might have. That being said I recommend starting with the following resources:
- Email address: this Wikipedia article is a good starting point because it’s rather practical and succinct.
- RFC 5322: in this RFC one should expect to learn about the formal specification about the standard syntax of an email address.
- net/mail’s implementation: implementation details matter.