Go Language - Validate Email Address Example

Email validation is required in nearly every application that has user registration in place. An email has its own structure, and before using it, we need to validate it. In Go Language, email validation can be performed by using the standard library function mail.ParseAddress() or regular expression.

Solution 1: Using the standard library function mail.ParseAddress()

package main

import (
"fmt"
"net/mail"
)

// Main function
func main() {
fmt.Println(ValidateEmail("knowledgefactory-gmail.com"))
fmt.Println(ValidateEmail("knowledgefactory4u@gmail.com"))
fmt.Println(ValidateEmail("knowledge-factory4u@gmail.com"))
}

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


Output:




Solution 2: Using regular expression

package main

import (
"fmt"
"regexp"
)

// Main function
func main() {
fmt.Println(ValidateEmail("knowledgefactory-gmail.com"))
fmt.Println(ValidateEmail("knowledgefactory4u@gmail.com"))
fmt.Println(ValidateEmail("knowledge-factory4u@gmail.com"))
}

func ValidateEmail(email string) bool {
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])?)*$"
emailRegex := regexp.MustCompile(pattern)
return emailRegex.MatchString(email)
}


Output:

Comments

Popular posts from this blog

Spring Boot OpenAI Integration: Step-by-Step Guide

Orchestration-Based Saga Architecture and Spring Boot Microservices Implementation Guide

Spring Boot 3 + Angular 15 + Material - Full Stack CRUD Application Example