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 functionfunc 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}
package main
import ( "fmt" "net/mail")
// Main functionfunc 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 functionfunc 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)}
package main
import ( "fmt" "regexp")
// Main functionfunc 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)}