Golang : Validate email address with regular expression
This short tutorial is add on to my previous tutorial on how to validate email address with Golang. This time, the validation is done with regular expression instead of invoking external function.
There are couple of regular expressions that can be used to validate an email address. For this tutorial, we will use this
^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,4}$
regular expression to validate the email address.
package main
import (
"fmt"
"regexp"
)
func validateEmail(email string) bool {
Re := regexp.MustCompile(`^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,4}$`)
return Re.MatchString(email)
}
func main() {
email := "abc@abc12"
if !validateEmail(email) {
fmt.Println("Email address is invalid")
} else {
fmt.Println("Email address is VALID")
}
email = "abc@abc123.com"
if !validateEmail(email) {
fmt.Println("Email address is invalid")
} else {
fmt.Println("Email address is VALID")
}
}
Sample output :
Email address is invalid
Email address is VALID
Note :
Some people, when confronted with a problem, think, “I know, I’ll use regular expressions.” Now they have two problems. — Jamie Zawinksi
Reference :
https://groups.google.com/forum/#!topic/golang-nuts/UAq5fio6xBQ
See also : Golang : Validate email address
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+10k Golang : Print how to use flag for your application example
+13k Golang : List objects in AWS S3 bucket
+5.3k Golang : Qt update UI elements with core.QCoreApplication_ProcessEvents
+14.3k Golang : How to filter a map's elements for faster lookup
+27.2k Golang : Convert CSV data to JSON format and save to file
+10.5k Golang : ISO8601 Duration Parser example
+24.4k Golang : How to print rune, unicode, utf-8 and non-ASCII CJK(Chinese/Japanese/Korean) characters?
+12.3k Golang : Search and extract certain XML data example
+9.3k Golang : Scramble and unscramble text message by randomly replacing words
+7k Golang : Get environment variable
+9.8k Golang : Sort and reverse sort a slice of integers
+15.1k Golang : Get timezone offset from date or timestamp