-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathemail.go
43 lines (32 loc) · 1.24 KB
/
email.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package types
import (
"errors"
"fmt"
"regexp"
"github.com/go-json-experiment/json"
"github.com/go-json-experiment/json/jsontext"
)
// regex from https://emailregex.com/
var reEmail = regexp.MustCompile(`(?m)(?:[a-z0-9!#$%&'*+/=?^_` + "`" + `{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_` + "`" + `{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])`)
// ErrInvalidEmail is returned when an email is invalid.
var ErrInvalidEmail = errors.New("invalid email")
// Email is a string that represents an email address.
type Email string
// Validate checks if the email is valid.
func (e Email) Validate() error {
if !reEmail.MatchString(string(e)) {
return fmt.Errorf("%w: %q", ErrInvalidEmail, e)
}
return nil
}
func (e *Email) UnmarshalJSONV2(dec *jsontext.Decoder, _ json.Options) error {
s := ""
if err := json.UnmarshalDecode(dec, &s); err != nil {
return err
}
if s == "" {
return nil // no email
}
*e = Email(s)
return e.Validate()
}