How to Validate Email in Go

Sheeraz Gul Feb 02, 2024
  1. Use Regex to Create a GoLang Email Validator
  2. Use Mail API to Create a GoLang Email Validator
  3. Create a Method for a GoLang Email Validator
How to Validate Email in Go

This tutorial demonstrates how to validate an email in GoLang.

Emails require a particular format; otherwise, they will not work. That is why email validation is significant when building an email system. This tutorial demonstrates different methods for validating an email in GoLang.

Use Regex to Create a GoLang Email Validator

The regex is used to validate different formats for different programming languages. GoLang also provides a package regexp to validate different formats and can be used for email validation.

Let’s try an example:

package main

import (
	"fmt"
	"regexp"
)

func main() {
	string1 := "delftstack.123@hotmail.com"
	string2 := "demo@delftstack.com"
	string3 := "demo@delftstack.tv"
	string4 := "demohotmail.com"
	string5 := "demo@"

	// regex pattern for email ^[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])?)*$
	RegexPattern := 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])?)*$")

	fmt.Printf("Email 1: %v :%v\n", string1, RegexPattern.MatchString(string1))
	fmt.Printf("Email 2: %v :%v\n", string2, RegexPattern.MatchString(string2))
	fmt.Printf("Email 3: %v :%v\n", string3, RegexPattern.MatchString(string3))
	fmt.Printf("Email 4: %v :%v\n", string4, RegexPattern.MatchString(string4))
	fmt.Printf("Email 5: %v :%v\n", string5, RegexPattern.MatchString(string5))
	fmt.Printf("\nThe regex email pattern: %v\n", RegexPattern.String())

}

The code above will validate the email based on the regular expression using the regexp package of the Go language. See the output for the above code:

Email 1: delftstack.123@hotmail.com :true
Email 2: demo@delftstack.com :true
Email 3: demo@delftstack.tv :true
Email 4: demohotmail.com :false
Email 5: demo@ :false

The regex email pattern: ^[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])?)*$

Use Mail API to Create a GoLang Email Validator

The mail API of GoLang has a method mail.ParseAddress used for email validation. This function parses the RFC 5322 address, and we can also check if a string is an email by using the name <local-part@domain> format.

Let’s see how to implement an email validator using the mail.ParseAddress method:

package main

import (
	"fmt"
	"net/mail"
)

func EmailValidator(EmailAddress string) (string, bool) {
	a, b := mail.ParseAddress(EmailAddress)
	if b != nil {
		return "", false
	}
	return a.Address, true
}

var EmailAddresses = []string{
	"delftstack.123@hotmail.com",
	"Delftstack <demo@delftstack.com>",
	"demo@delftstack.tv",
	"demohotmail.com",
	"demo@",
}

func main() {
	for _, e_address := range EmailAddresses {
		if emailaddress, ok := EmailValidator(e_address); ok {
			fmt.Printf("The Input: %-30s Valadity: %-10t Email Address: %s\n", e_address, ok, emailaddress)
		} else {
			fmt.Printf("The Input: %-30s Valadity: %-10t\n", e_address, ok)
		}
	}
}

The code above creates a function as EmailValidator by using the mail.ParseAddress method. The code checks the validation of an array of emails.

See the output:

The Input: delftstack.123@hotmail.com     Valadity: true       Email Address: delftstack.123@hotmail.com
The Input: Delftstack <demo@delftstack.com> Valadity: true       Email Address: demo@delftstack.com
The Input: demo@delftstack.tv             Valadity: true       Email Address: demo@delftstack.tv
The Input: demohotmail.com                Valadity: false
The Input: demo@                          Valadity: false

Create a Method for a GoLang Email Validator

Suppose you find the regular expression difficult or have ambiguity in loading packages. In that case, you can also create a method based on the GoLang code to validate an email based on the standard format.

Here is an example:

package main

import (
	"fmt"
	"strings"
	"unicode"
)

func EmailValidator(emailaddress string) bool {
	if emailaddress == "" {
		return false
	}
	if CheckSpace(emailaddress) {
		return false
	}

	AttheRate := strings.IndexByte(emailaddress, '@')
	if AttheRate == -1 {
		return false
	}

	localPart := emailaddress[:AttheRate]
	if localPart == "" {
		return false
	}

	DomainCheck := emailaddress[AttheRate+1:]
	if DomainCheck == "" {
		return false
	}

	LastDot := strings.IndexByte(DomainCheck, '.')
	if LastDot == -1 || LastDot == 0 || LastDot == len(DomainCheck)-1 {
		return false
	}

	if strings.Index(DomainCheck, "..") != -1 {
		return false
	}

	AfterDot := strings.LastIndexByte(DomainCheck, '.')
	return 2 <= len([]rune(DomainCheck[AfterDot+1:]))
}

func CheckSpace(emailaddress string) bool {
	for _, a := range emailaddress {
		if unicode.IsSpace(a) {
			return true
		}
	}
	return false
}

func main() {
	string1 := "delftstack.123@hotmail.com"
	string2 := "demo@delftstack.com"
	string3 := "demo@delftstack.tv"
	string4 := "demohotmail.com"
	string5 := "demo@"

	fmt.Printf("Email 1: %v :%v\n", string1, EmailValidator(string1))
	fmt.Printf("Email 2: %v :%v\n", string2, EmailValidator(string2))
	fmt.Printf("Email 3: %v :%v\n", string3, EmailValidator(string3))
	fmt.Printf("Email 4: %v :%v\n", string4, EmailValidator(string4))
	fmt.Printf("Email 5: %v :%v\n", string5, EmailValidator(string5))

}

The code above creates a method purely based on the GoLang code to check the email validation. Let’s see the output:

Email 1: delftstack.123@hotmail.com :true
Email 2: demo@delftstack.com :true
Email 3: demo@delftstack.tv :true
Email 4: demohotmail.com :false
Email 5: demo@ :false
Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook