Introduction:
Email addresses are a critical part of modern communication, but ensuring that they are properly formatted is important for both validation and security purposes. This program demonstrates how to validate whether a given string is a properly formatted email address using the Go programming language. The goal is to verify that the email follows the structure of `localpart@domain` and includes proper characters, domain name, and a valid extension like `.com` or `.org`.
Objective:
The objective of this program is to write a Go program that takes an email address as input and checks whether it is properly formatted. If the email is valid, it will return `true`; otherwise, it will return `false`.
Code:
package main import ( "fmt" "regexp" ) // Function to validate email address func isValidEmail(email string) bool { // Define a regex pattern for email validation pattern := `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$` re := regexp.MustCompile(pattern) // Check if the email matches the pattern return re.MatchString(email) } func main() { var email string fmt.Println("Enter email address to validate:") fmt.Scanln(&email) // Validate the email if isValidEmail(email) { fmt.Println("The email address is valid.") } else { fmt.Println("The email address is invalid.") } }
Explanation of the Program Structure:
This Go program works by utilizing regular expressions (regex) to validate email addresses. Here is a breakdown of the key sections:
- Imports: The program imports two essential packages:
fmt
: for reading user input and printing the output to the console.regexp
: for working with regular expressions to match patterns in strings.
- isValidEmail function: This function accepts a string (email) and uses a regex pattern to check if the email matches the typical email format. The regex pattern matches a string that has a local part (e.g., `user.name`), followed by the `@` symbol, and then the domain part with a valid extension (e.g., `.com`). If the string matches the pattern, the function returns `true`; otherwise, it returns `false`.
- Main function: In the main function, the program prompts the user to input an email address. The input is passed to the `isValidEmail` function, which checks if the email is valid. The result is displayed to the user, informing them whether the email is valid or invalid.
How to Run the Program:
- Ensure that you have Go installed on your machine. If not, download and install Go from the official site: https://go.dev/dl/.
- Save the code in a file named
email_validator.go
. - Open your terminal or command prompt and navigate to the directory where
email_validator.go
is saved. - Run the command:
go run email_validator.go
to execute the program. - Enter an email address when prompted and the program will tell you whether it is valid or invalid.