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 = "[email protected]"
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
+5.7k Golang : Detect variable or constant type
+22.3k Golang : Set and Get HTTP request headers example
+5.4k Golang : Configure crontab to poll every two minutes 8am to 6pm Monday to Friday
+23.6k Golang : Use regular expression to validate domain name
+12.4k Golang : Remove or trim extra comma from CSV
+9.2k Facebook : Getting the friends list with PHP return JSON format
+4.4k MariaDB/MySQL : How to get version information
+5.9k Golang : Debug with Godebug
+10.3k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+5.6k Unix/Linux : How to open tar.gz file ?
+5.4k Unix/Linux/MacOSx : Get local IP address
+12k Golang : Print UTF-8 fonts on image example