Add ValidateEmail and NormalizeGiftCardCode functions with comprehensive tests. Migrate guest.go from inline mail.ParseAddress to validators.ValidateEmail. Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent) Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
41 lines
1.0 KiB
Go
41 lines
1.0 KiB
Go
package validators
|
|
|
|
import (
|
|
"errors"
|
|
"net/mail"
|
|
"regexp"
|
|
"strings"
|
|
)
|
|
|
|
var emailRegex = regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)
|
|
|
|
// ValidateEmail checks that an email is non-empty, within length limits,
|
|
// and conforms to both RFC 5322 (via net/mail) and a basic regex shape.
|
|
func ValidateEmail(email string) error {
|
|
email = strings.TrimSpace(email)
|
|
if email == "" {
|
|
return errors.New("email is required")
|
|
}
|
|
if len(email) > 254 {
|
|
return errors.New("email exceeds maximum length of 254 characters")
|
|
}
|
|
if _, err := mail.ParseAddress(email); err != nil {
|
|
return errors.New("invalid email format")
|
|
}
|
|
if !emailRegex.MatchString(email) {
|
|
return errors.New("invalid email format")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// NormalizeGiftCardCode strips non-alphanumeric characters and upper-cases the code.
|
|
func NormalizeGiftCardCode(code string) string {
|
|
clean := ""
|
|
for _, char := range code {
|
|
if (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') || (char >= '0' && char <= '9') {
|
|
clean += string(char)
|
|
}
|
|
}
|
|
return clean
|
|
}
|