Try it yourself with our free Regex Tester tool — runs entirely in your browser, no signup needed.

How to Validate email addresses with regex in Go

How to Validate Email Addresses with Regex in Go

Validating email addresses is a crucial step in many applications, ensuring that user input is correct and helping to prevent spam and abuse. In this article, we'll explore how to use regular expressions (regex) in Go to validate email addresses efficiently and effectively.

Quick Example

Here's a minimal example that demonstrates how to validate an email address using regex in Go:

package main

import (
	"regexp"
	"fmt"
)

func main() {
	email := "example@example.com"
	regex := regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)
	if regex.MatchString(email) {
		fmt.Println("Email is valid")
	} else {
		fmt.Println("Email is invalid")
	}
}

Step-by-Step Breakdown

Let's walk through the code line by line:

  • import "regexp": We import the regexp package, which provides support for regular expressions in Go.
  • email := "example@example.com": We define a sample email address to validate.
  • regex := regexp.MustCompile(^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$): We compile a regex pattern using regexp.MustCompile. The pattern used here is a simplified version of the official specification for email addresses (RFC 5322). It breaks down as follows:
    • ^ matches the start of the string.
    • [a-zA-Z0-9._%+-]+ matches one or more alphanumeric characters, dots, underscores, percent signs, plus signs, or hyphens.
    • @ matches the @ symbol.
    • [a-zA-Z0-9.-]+ matches one or more alphanumeric characters, dots, or hyphens.
    • \. matches a period (escaped with a backslash because . has a special meaning in regex).
    • [a-zA-Z]{2,} matches the domain extension (it must be at least 2 characters long).
    • $ matches the end of the string.
  • if regex.MatchString(email) { ... }: We use the MatchString method to check if the email address matches the regex pattern. If it does, we print "Email is valid".

Handling Edge Cases

Here are a few common edge cases to consider:

Empty/null input

func main() {
	email := ""
	regex := regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)
	if regex.MatchString(email) {
		fmt.Println("Email is valid")
	} else {
		fmt.Println("Email is invalid")
	}
}

Output: "Email is invalid"

Invalid input

func main() {
	email := " invalid@example.com"
	regex := regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)
	if regex.MatchString(email) {
		fmt.Println("Email is valid")
	} else {
		fmt.Println("Email is invalid")
	}
}

Output: "Email is invalid"

Large input

func main() {
	email := strings.Repeat("a", 1000) + "@example.com"
	regex := regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)
	if regex.MatchString(email) {
		fmt.Println("Email is valid")
	} else {
		fmt.Println("Email is invalid")
	}
}

Output: "Email is invalid" (because the local part is too long)

Unicode/special characters

func main() {
	email := "example@éxample.com"
	regex := regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)
	if regex.MatchString(email) {
		fmt.Println("Email is valid")
	} else {
		fmt.Println("Email is invalid")
	}
}

Output: "Email is invalid" (because the domain contains non-ASCII characters)

Common Mistakes

Here are a few common mistakes to watch out for:

Mistake 1: Using a too-permissive pattern

regex := regexp.MustCompile(`.+@.+`)

This pattern matches almost any string, including invalid email addresses.

Mistake 2: Not handling null input

if regex.MatchString(email) {
    // ...
} else {
    panic("Email is invalid")
}

This code panics if the input is null, instead of handling it gracefully.

Mistake 3: Not using a compiled regex

if regexp.MatchString(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`, email) {
    // ...
}

This code recompiles the regex pattern every time it's used, which can be inefficient.

Performance Tips

Here are a few performance tips to keep in mind:

  • Use a compiled regex pattern to avoid recompiling it every time it's used.
  • Use a efficient regex pattern that minimizes backtracking.
  • Consider using a specialized email validation library that's optimized for performance.

FAQ

Q: What's the best way to validate email addresses?

A: The best way to validate email addresses is to use a combination of regex and additional checks, such as checking the domain's MX records.

Q: Can I use this regex pattern for all email addresses?

A: No, this regex pattern is a simplified version of the official specification and may not match all valid email addresses.

Q: How can I handle internationalized domain names (IDNs)?

A: You can use a library like golang.org/x/text/unicode/norm to normalize IDNs before validating them.

Q: Can I use this code in a production environment?

A: Yes, this code is suitable for production use, but you should consider adding additional error handling and logging.

Q: How can I test this code?

A: You can test this code using a variety of email addresses, including valid and invalid ones, as well as edge cases like null input and large input.

AI agent tools available. The CodeTidy MCP Server gives Claude, Cursor, and other AI agents access to 60+ developer tools. One command: npx @codetidy/mcp