Skip to content

Instantly share code, notes, and snippets.

@Lukmanern
Created January 30, 2024 15:13
Show Gist options
  • Save Lukmanern/5ac14343fa14c03ec0f029d39473d085 to your computer and use it in GitHub Desktop.
Save Lukmanern/5ac14343fa14c03ec0f029d39473d085 to your computer and use it in GitHub Desktop.
Golang Email Validation ; your choices.
package main
import (
"fmt"
"net/mail"
"github.com/fatih/color"
"github.com/go-playground/validator/v10"
)
type User struct {
Email string `validate:"required,email"`
}
func main() {
users := []User{
{Email: "simple.valid.email@email.test"}, // valid -1
{Email: "simple.valid.email@sub1.sub2.email.test"}, // valid -2
{Email: "simple.valid.email@email.test."}, // valid too (?) -3
{Email: "simple.valid.email@sub1..sub2..email.test"}, // valid too (?) -4
{Email: "simple.valid.email@email.test.."}, // invalid -1
{Email: "simple.valid.email@.email.test"}, // invalid -2
{Email: "simple.valid.email.@email.test"}, // invalid -3
{Email: "simple.valid.email@email.test_"}, // invalid -4
{Email: "simple.valid.email@email.test`"}, // invalid -5
{Email: "simple.valid.email@email..test"}, // invalid -6
{Email: "simple.valid..email@email.test"}, // invalid -7
{Email: ".simple.valid.email@email.test"}, // invalid -8
{Email: "..simple.valid.email@email.test"}, // invalid -9
}
fmt.Println("\nusing github.com/go-playground/validator/v10")
for _, user := range users {
validate := validator.New()
if err := validate.Struct(&user); err != nil {
printInvalid(user.Email, err.Error())
continue
}
printValid(user.Email)
}
fmt.Println("\n\nusing net/mail")
for _, user := range users {
_, err := mail.ParseAddress(user.Email)
if err != nil {
printInvalid(user.Email, err.Error())
continue
}
printValid(user.Email)
}
}
func printValid(email string) {
color.Green("email is valid, email: " + email)
}
func printInvalid(email, errMsg string) {
color.New(color.FgHiRed).Println(errMsg, ", email:", email)
}
@Lukmanern
Copy link
Author

Screenshot (3236)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment