An e mail handle in Golang may be validated utilizing the usual library perform mail.ParseAddress
. This perform parses an RFC 5322 handle, however through the use of it appropriately, we will additionally test if a string is a sound e mail handle and get it from the "title <local-part@area>"
format.
package deal fundamental
import (
"fmt"
"internet/mail"
)
func validMailAddress(handle string) (string, bool) {
addr, err := mail.ParseAddress(handle)
if err != nil {
return "", false
}
return addr.Handle, true
}
var addresses = []string{
"foo@gmail.com",
"Gopher <from@instance.com>",
"instance",
}
func fundamental() {
for _, a := vary addresses {
if addr, okay := validMailAddress(a); okay {
fmt.Printf("worth: %-30s legitimate e mail: %-10t handle: %sn", a, okay, addr)
} else {
fmt.Printf("worth: %-30s legitimate e mail: %-10tn", a, okay)
}
}
}
Output:
worth: foo@gmail.com legitimate e mail: true handle: foo@gmail.com
worth: Gopher <from@instance.com> legitimate e mail: true handle: from@instance.com
worth: instance legitimate e mail: false