Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions utils/regex.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Copyright © 2025 Prabhjot Singh Sethi, All Rights reserved
// Author: Prabhjot Singh Sethi <prabhjot.sethi@gmail.com>

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)
}
34 changes: 34 additions & 0 deletions utils/regex_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Copyright © 2025 Prabhjot Singh Sethi, All Rights reserved
// Author: Prabhjot Singh Sethi <prabhjot.sethi@gmail.com>

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)
}
}
}