Skip to content

Commit

Permalink
added handling a list of emails
Browse files Browse the repository at this point in the history
  • Loading branch information
petrohordiienko committed Dec 7, 2020
1 parent 410bf76 commit aff139c
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 12 deletions.
1 change: 1 addition & 0 deletions README.md
Expand Up @@ -173,6 +173,7 @@ Send request to the server using curl or postman: `curl GET "http://localhost:90
* `uuid_v3` The field under validation must be a valid UUID V3.
* `uuid_v4` The field under validation must be a valid UUID V4.
* `uuid_v5` The field under validation must be a valid UUID V5.
* `list:email` The field under validation must be a list of valid emails.

### Add Custom Rules

Expand Down
3 changes: 3 additions & 0 deletions go.mod
@@ -0,0 +1,3 @@
module github.com/numarqe/govalidator

go 1.13
43 changes: 31 additions & 12 deletions rules.go
Expand Up @@ -38,8 +38,19 @@ func validateCustomRules(field string, rule string, message string, value interf
}
}

func init() {
func emailRule(field, rule, message string, value interface{}) error {
str := toString(value)
err := fmt.Errorf("The %s field must be a valid email address", field)
if message != "" {
err = errors.New(message)
}
if !isEmail(str) {
return err
}
return nil
}

func init() {
// Required check the Required fields
AddCustomRule("required", func(field, rule, message string, value interface{}) error {
err := fmt.Errorf("The %s field is required", field)
Expand Down Expand Up @@ -510,17 +521,7 @@ func init() {
})

// Email check the provided field is valid Email
AddCustomRule("email", func(field string, rule string, message string, value interface{}) error {
str := toString(value)
err := fmt.Errorf("The %s field must be a valid email address", field)
if message != "" {
err = errors.New(message)
}
if !isEmail(str) {
return err
}
return nil
})
AddCustomRule("email", emailRule)

// validFloat check the provided field is valid float number
AddCustomRule("float", func(field string, rule string, message string, value interface{}) error {
Expand Down Expand Up @@ -1078,4 +1079,22 @@ func init() {
}
return nil
})

AddCustomRule("list", func(field string, rule string, message string, value interface{}) error {
var subRule string
if strings.Contains(rule, ":") {
subRule = strings.Split(rule, ":")[1]
}
switch subRule {
case "email":
for _, email := range value.([]string) {
if err := emailRule(field, rule, message, email); err != nil {
return err
}
}
break
}

return nil
})
}

0 comments on commit aff139c

Please sign in to comment.