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:

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete