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

Spring boot video streaming example-HTML5

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

Registration and Login with Spring Boot + Spring Security + Thymeleaf

DataTable-Pagination example with Spring boot, jQuery and ajax

Spring Webflux File Download - REST API Example

Node JS mini projects with source code - free download

ReactJS, Spring Boot JWT Authentication Example