emailgoemail-validation

How to validate an email address in Golang


I have checked StackOverflow and couldn't find any question that answers "how do I validate an email address in Go?".

After some research, I solved it to fill my need.

I have this regex and function in Go, which work fine:

import (
    "fmt"
    "regexp"
)

func main() {
    fmt.Println(isEmailValid("test44@gmail.com")) // true
    fmt.Println(isEmailValid("test$@gmail.com")) // true -- expected "false" 
}


// isEmailValid checks if the email provided is valid by regex.
func isEmailValid(e string) bool {
    emailRegex := 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])?)*$")
    return emailRegex.MatchString(e)
}

The problem is that it allows special characters that I don't want. I tried to use some from other languages' regex expression, but it throws the error "unknown escape" in debug.

Could anyone correct my regex or suggest another Go module?


Solution

  • The standard lib has email parsing and validation built in, simply use: mail.ParseAddress().

    A simple "is-valid" test:

    func valid(email string) bool {
        _, err := mail.ParseAddress(email)
        return err == nil
    }
    

    Testing it:

    for _, email := range []string{
        "good@exmaple.com",
        "bad-example",
    } {
        fmt.Printf("%18s valid: %t\n", email, valid(email))
    }
    

    Which outputs (try it on the Go Playground):

      good@exmaple.com valid: true
           bad-example valid: false
    

    NOTE:

    The net/mail package implements and follows the RFC 5322 specification (and extension by RFC 6532). This means a seemingly bad email address like bad-example@t is accepted and parsed by the package because it's valid according to the spec. t may be a valid local domain name, it does not necessarily have to be a public domain. net/mail does not check if the domain part of the address is a public domain, nor that it is an existing, reachable public domain.