Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate an email address in Go

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?

like image 718
Riyaz Khan Avatar asked Mar 14 '21 11:03

Riyaz Khan


People also ask

How do I know if an email address is invalid?

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.

How do I validate my SMTP address?

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.

How do I validate an email address?

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.

How to validate a standard email using regex?

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) }

How to check if an email address is correct?

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.

Can I manually check the validity of email?

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.


Video Answer


2 Answers

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
like image 73
icza Avatar answered Oct 24 '22 16:10

icza


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
like image 29
Riyaz Khan Avatar answered Oct 24 '22 17:10

Riyaz Khan