validate an email in go

To validate an email in Go, we can use regular expressions or regex. Here's an example function that uses regex to validate an email:

main.go
import (
    "fmt"
    "regexp"
)

func isValidEmail(email string) bool {
    // Regex pattern for validating email
    pattern := `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`
    
    // Compile the regex pattern
    regex := regexp.MustCompile(pattern)
    
    // Validate the email
    return regex.MatchString(email)
}

func main() {
    email := "example@example.com" // Valid email
    isValid := isValidEmail(email)
    fmt.Println(email, "is valid:", isValid)
    
    email = "example@" // Invalid email
    isValid = isValidEmail(email)
    fmt.Println(email, "is valid:", isValid)
}
601 chars
26 lines

In the above code, the isValidEmail function takes an email as an argument and uses a regex pattern to validate it. The Pattern variable holds the regular expression pattern for validating an email. We then compile the pattern using the Compile method of the regexp package. Finally, we validate the email by using the MatchString method of the regex object. If the email is valid, the function returns true, otherwise, it returns false.

gistlibby LogSnag