Skip to content

Commit 24dcf2a

Browse files
committed
fix: improve email validation using net/mail package
1 parent 912bc9f commit 24dcf2a

File tree

3 files changed

+8
-13
lines changed

3 files changed

+8
-13
lines changed

types/email.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package types
33
import (
44
"encoding/json"
55
"errors"
6+
"net/mail"
67
)
78

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

1617
func (e Email) MarshalJSON() ([]byte, error) {
17-
if !emailRegex.MatchString(string(e)) {
18+
if _, err := mail.ParseAddress(string(e)); err != nil {
1819
return nil, ErrValidationEmail
1920
}
2021

@@ -32,7 +33,7 @@ func (e *Email) UnmarshalJSON(data []byte) error {
3233
}
3334

3435
*e = Email(s)
35-
if !emailRegex.MatchString(s) {
36+
if _, err := mail.ParseAddress(s); err != nil {
3637
return ErrValidationEmail
3738
}
3839

types/email_test.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,11 @@ func TestEmail_MarshalJSON_Validation(t *testing.T) {
2222
expectedJSON: []byte(`{"email":"validemail@openapicodegen.com"}`),
2323
expectedError: nil,
2424
},
25+
"it should succeed marshalling a valid email and return valid JSON populated with the email with valid separators": {
26+
email: Email("validemail+with_valid-separator{like}~these*ones@openapicodegen.com"),
27+
expectedJSON: []byte(`{"email":"validemail+with_valid-separator{like}~these*ones@openapicodegen.com"}`),
28+
expectedError: nil,
29+
},
2530
"it should fail marshalling an invalid email and return a validation error": {
2631
email: Email("invalidemail"),
2732
expectedJSON: nil,

types/regexes.go

Lines changed: 0 additions & 11 deletions
This file was deleted.

0 commit comments

Comments
 (0)