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("[email protected]")) // true
fmt.Println(isEmailValid("[email protected]")) // 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?
It's important to understand that every valid email must contain an “@” symbol before the domain. An invalid email address will likely have spelling or formatting errors in the local part of the email or a “dead” domain name.
After the DNS lookup, you can verify the email address via SMTP connection. You need to connect to the chosen SMTP server and check if an email address exists. If the server replies with (250 OK), the email address is valid.
Validating email addresses, like many thing, are one of those things you can put any amount of effort you want into. The solutions range from nice’n’quick, by using regex to check the email address is formatted correctly - through to complicated, by actually trying to interface with the remote server.
Therefore, I went to the regex solution to validate standard emails: func isEmailValid (e string) bool { emailRegex := regexp.MustCompile (`^ [a-z0-9._%+\-]+@ [a-z0-9.\-]+\. [a-z] {2,4}$`) return emailRegex.MatchString (e) }
Check if an email address is correct and really exists using the go programming language An Email Address can look right but still be wrong and bounce. Real Email uses in depth email address validation to check if emails really exist without sending any messages.
It would be impossible to manually check the validity of every single email you receive, which is why you should always start by using Clean Email to organize all of your emails into easy-to-review bundles that you can manage just as easily as if you were managing a single email.
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{
"[email protected]",
"bad-example",
} {
fmt.Printf("%18s valid: %t\n", email, valid(email))
}
Which outputs (try it on the Go Playground):
[email protected] valid: true
bad-example valid: false
The above approach from @icza is nice, however, if we use it in login/signup form validation, many people will enter a partial or incorrect email address, which will create a bunch of invalid records in production. Furthermore, who knows we might get killed because of that😅.
Therefore, I went to the regex solution to validate standard emails:
Here is the code:
func isEmailValid(e string) bool {
emailRegex := regexp.MustCompile(`^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,4}$`)
return emailRegex.MatchString(e)
}
Test Cases:
fmt.Println(isEmailValid("[email protected]")) // true
fmt.Println(isEmailValid("bad-email")) // false
fmt.Println(isEmailValid("[email protected]")) // false
fmt.Println(isEmailValid("test-email.com")) // false
fmt.Println(isEmailValid("[email protected]")) // true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With