Skip to content

How to Validate email address in GoLang ?

ValidateEmail checks if the given string is a valid email address.

It uses the mail.ParseAddress function from the net/mail package to parse the email address. If the email address is valid, it returns true; otherwise, it returns false.

Parameters:

  • email: the email address to be validated.

Returns:

  • bool: true if the email address is valid, false otherwise.
import (
	"net/mail"
)
func ValidateEmail(email string) bool {
	// Parse the email address using mail.ParseAddress
	_, err := mail.ParseAddress(email)

	// If there is no error, the email address is valid
	return err == nil
}

Experience the magic of coding unfold as you execute this code!

package main

import (
	"fmt"
	"net/mail"
)

func ValidateEmail(email string) bool {
	_, err := mail.ParseAddress(email)
	return err == nil
}

func main() {
	for _, email := range []string{
		"good@exmaple.com",
		"bad-example",
		"good@gmail.com",
		"good@gmail",
		"good.com",
		"good.id@gmail.com",
	} {
		fmt.Printf("%s is valid: %t \n", email, ValidateEmail(email))
	}

	fmt.Println("Build with love by Adam Nasrudin")
}

enjoy your code!