File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package types
2+
3+ import (
4+ "encoding/json"
5+ "errors"
6+ )
7+
8+ type Email string
9+
10+ func (e Email ) MarshalJSON () ([]byte , error ) {
11+ if ! emailRegex .MatchString (string (e )) {
12+ return nil , errors .New ("email: failed to pass regex validation" )
13+ }
14+ return json .Marshal (string (e ))
15+ }
16+
17+ func (e * Email ) UnmarshalJSON (data []byte ) error {
18+ var s string
19+ if err := json .Unmarshal (data , & s ); err != nil {
20+ return err
21+ }
22+ if ! emailRegex .MatchString (s ) {
23+ return errors .New ("email: failed to pass regex validation" )
24+ }
25+ * e = Email (s )
26+ return nil
27+ }
Original file line number Diff line number Diff line change 1+ package types
2+
3+ import (
4+ "encoding/json"
5+ "testing"
6+
7+ "github.com/stretchr/testify/assert"
8+ )
9+
10+ func TestEmail_MarshalJSON (t * testing.T ) {
11+ testEmail := "gaben@valvesoftware.com"
12+ b := struct {
13+ EmailField Email `json:"email"`
14+ }{
15+ EmailField : Email (testEmail ),
16+ }
17+ jsonBytes , err := json .Marshal (b )
18+ assert .NoError (t , err )
19+ assert .JSONEq (t , `{"email":"gaben@valvesoftware.com"}` , string (jsonBytes ))
20+ }
21+
22+ func TestEmail_UnmarshalJSON (t * testing.T ) {
23+ testEmail := Email ("gaben@valvesoftware.com" )
24+ jsonStr := `{"email":"gaben@valvesoftware.com"}`
25+ b := struct {
26+ EmailField Email `json:"email"`
27+ }{}
28+ err := json .Unmarshal ([]byte (jsonStr ), & b )
29+ assert .NoError (t , err )
30+ assert .Equal (t , testEmail , b .EmailField )
31+ }
Original file line number Diff line number Diff line change 1+ package types
2+
3+ import "regexp"
4+
5+ const (
6+ emailRegexString = "^(?:(?:(?:(?:[a-zA-Z]|\\ d|[!#\\ $%&'\\ *\\ +\\ -\\ /=\\ ?\\ ^_`{\\ |}~]|[\\ x{00A0}-\\ x{D7FF}\\ x{F900}-\\ x{FDCF}\\ x{FDF0}-\\ x{FFE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 x{FDF0}-\\ x{FFEF}])(?:[a-zA-Z]|\\ d|-|\\ .|~|[\\ x{00A0}-\\ x{D7FF}\\ x{F900}-\\ x{FDCF}\\ x{FDF0}-\\ x{FFEF}])*(?:[a-zA-Z]|[\\ x{00A0}-\\ x{D7FF}\\ x{F900}-\\ x{FDCF}\\ x{FDF0}-\\ x{FFEF}])))\\ .?$"
7+ )
8+
9+ var (
10+ emailRegex = regexp .MustCompile (emailRegexString )
11+ )
You can’t perform that action at this time.
0 commit comments