Skip to content

fix: improve email validation using net/mail package #60

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
11 changes: 7 additions & 4 deletions types/email.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package types
import (
"encoding/json"
"errors"
"net/mail"
)

// ErrValidationEmail is the sentinel error returned when an email fails validation
Expand All @@ -14,11 +15,12 @@ var ErrValidationEmail = errors.New("email: failed to pass regex validation")
type Email string

func (e Email) MarshalJSON() ([]byte, error) {
if !emailRegex.MatchString(string(e)) {
m, err := mail.ParseAddress(string(e))
if err != nil {
return nil, ErrValidationEmail
}

return json.Marshal(string(e))
return json.Marshal(m.Address)
}

func (e *Email) UnmarshalJSON(data []byte) error {
Expand All @@ -31,10 +33,11 @@ func (e *Email) UnmarshalJSON(data []byte) error {
return err
}

*e = Email(s)
if !emailRegex.MatchString(s) {
m, err := mail.ParseAddress(s)
if err != nil {
return ErrValidationEmail
}

*e = Email(m.Address)
return nil
}
5 changes: 5 additions & 0 deletions types/email_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ func TestEmail_MarshalJSON_Validation(t *testing.T) {
expectedJSON: []byte(`{"email":"[email protected]"}`),
expectedError: nil,
},
"it should succeed marshalling a valid email and return valid JSON populated with the email with valid separators": {
email: Email("validemail+with_valid-separator{like}~these*[email protected]"),
expectedJSON: []byte(`{"email":"validemail+with_valid-separator{like}~these*[email protected]"}`),
expectedError: nil,
},
"it should fail marshalling an invalid email and return a validation error": {
email: Email("invalidemail"),
expectedJSON: nil,
Expand Down
11 changes: 0 additions & 11 deletions types/regexes.go

This file was deleted.