How to validate an email address in Go

Issue

I have checked the StackOverflow and couldn’t find any question that answers how to validate email in Go Language.

After some research, I figured out and solved it as per my need.

I have this regex and Go function, 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 accepts the 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 give me a good regex or any fast solution (pkg) that works with GoLang?

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

Answered By – icza

Answer Checked By – Mary Flores (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.