diff --git a/utils/regex.go b/utils/regex.go new file mode 100644 index 0000000..e6e6daa --- /dev/null +++ b/utils/regex.go @@ -0,0 +1,17 @@ +// Copyright © 2025 Prabhjot Singh Sethi, All Rights reserved +// Author: Prabhjot Singh Sethi + +package utils + +import "regexp" + +// IsValidEmail returns true if the provided string is a valid email address format. +// Usage: +// +// valid := utils.IsValidEmail("user@example.com") // returns true +// valid := utils.IsValidEmail("not-an-email") // returns false +func IsValidEmail(email string) bool { + // This is a reasonably strict regex for email validation + var emailRegex = regexp.MustCompile(`^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$`) + return emailRegex.MatchString(email) +} diff --git a/utils/regex_test.go b/utils/regex_test.go new file mode 100644 index 0000000..3fcf24b --- /dev/null +++ b/utils/regex_test.go @@ -0,0 +1,34 @@ +// Copyright © 2025 Prabhjot Singh Sethi, All Rights reserved +// Author: Prabhjot Singh Sethi + +package utils + +import ( + "testing" +) + +func TestIsValidEmail(t *testing.T) { + tests := []struct { + input string + expected bool + }{ + {"test@example.com", true}, + {"invalid-email", false}, + {"user@localhost", false}, // usually considered invalid in public contexts + {"name.lastname@domain.co.uk", true}, + {"user@domain", false}, // missing TLD + {"user@sub.domain.com", true}, + {"user+alias@domain.com", true}, + {"", false}, + {"@domain.com", false}, + {"user@.com", false}, + {"user@domain.c", false}, // TLD too short + } + + for _, test := range tests { + result := IsValidEmail(test.input) + if result != test.expected { + t.Errorf("IsValidEmail(%q) = %v; want %v", test.input, result, test.expected) + } + } +}