Skip to content

Commit

Permalink
Merge branch 'master' into postcode-validator
Browse files Browse the repository at this point in the history
  • Loading branch information
deankarn authored May 6, 2021
2 parents 3ccc659 + c206620 commit d08f919
Show file tree
Hide file tree
Showing 6 changed files with 307 additions and 111 deletions.
73 changes: 73 additions & 0 deletions _examples/map-validation/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package main

import (
"fmt"
"github.com/go-playground/validator/v10"
)

var validate *validator.Validate

func main() {
validate = validator.New()

validateMap()
validateNestedMap()
}

func validateMap() {
user := map[string]interface{}{"name": "Arshiya Kiani", "email": "zytel3301@gmail.com"}

// Every rule will be applied to the item of the data that the offset of rule is pointing to.
// So if you have a field "email": "omitempty,required,email", the validator will apply these
// rules to offset of email in user data
rules := map[string]interface{}{"name": "required,min=8,max=32", "email": "omitempty,required,email"}

// ValidateMap will return map[string]error.
// The offset of every item in errs is the name of invalid field and the value
// is the message of error. If there was no error, ValidateMap method will
// return an EMPTY map of errors, not nil. If you want to check that
// if there was an error or not, you must check the length of the return value
errs := validate.ValidateMap(user, rules)

if len(errs) > 0 {
fmt.Println(errs)
// The user is invalid
}

// The user is valid
}

func validateNestedMap() {

data := map[string]interface{}{
"name": "Arshiya Kiani",
"email": "zytel3301@gmail.com",
"details": map[string]interface{}{
"family_members": map[string]interface{}{
"father_name": "Micheal",
"mother_name": "Hannah",
},
"salary": "1000",
},
}

// Rules must be set as the structure as the data itself. If you want to dive into the
// map, just declare its rules as a map
rules := map[string]interface{}{
"name": "min=4,max=32",
"email": "required,email",
"details": map[string]interface{}{
"family_members": map[string]interface{}{
"father_name": "required,min=4,max=32",
"mother_name": "required,min=4,max=32",
},
"salary": "number",
},
}

if len(validate.ValidateMap(data, rules)) == 0 {
// Data is valid
}

// Data is invalid
}
24 changes: 24 additions & 0 deletions baked_in.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ var (
"bcp47_language_tag": isBCP47LanguageTag,
"postcode_iso3166_alpha2": isPostcodeByIso3166Alpha2,
"postcode_iso3166_alpha2_field": isPostcodeByIso3166Alpha2Field,
"bic": isIsoBicFormat,
}
)

Expand Down Expand Up @@ -1040,6 +1041,9 @@ func isNeCrossStructField(fl FieldLevel) bool {
case reflect.Slice, reflect.Map, reflect.Array:
return int64(topField.Len()) != int64(field.Len())

case reflect.Bool:
return topField.Bool() != field.Bool()

case reflect.Struct:

fieldType := field.Type()
Expand Down Expand Up @@ -1087,6 +1091,9 @@ func isEqCrossStructField(fl FieldLevel) bool {
case reflect.Slice, reflect.Map, reflect.Array:
return int64(topField.Len()) == int64(field.Len())

case reflect.Bool:
return topField.Bool() == field.Bool()

case reflect.Struct:

fieldType := field.Type()
Expand Down Expand Up @@ -1134,6 +1141,9 @@ func isEqField(fl FieldLevel) bool {
case reflect.Slice, reflect.Map, reflect.Array:
return int64(field.Len()) == int64(currentField.Len())

case reflect.Bool:
return field.Bool() == currentField.Bool()

case reflect.Struct:

fieldType := field.Type()
Expand Down Expand Up @@ -1491,6 +1501,9 @@ func requireCheckFieldValue(fl FieldLevel, param string, value string, defaultNo

case reflect.Slice, reflect.Map, reflect.Array:
return int64(field.Len()) == asInt(value)

case reflect.Bool:
return field.Bool() == asBool(value)
}

// default reflect.String:
Expand Down Expand Up @@ -2345,3 +2358,14 @@ func isBCP47LanguageTag(fl FieldLevel) bool {

panic(fmt.Sprintf("Bad field type %T", field.Interface()))
}

// isIsoBicFormat is the validation function for validating if the current field's value is a valid Business Identifier Code (SWIFT code), defined in ISO 9362
func isIsoBicFormat(fl FieldLevel) bool {
bicString := fl.Field().String()

if !bicRegex.MatchString(bicString) {
return false
}

return true
}
7 changes: 7 additions & 0 deletions doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -1228,6 +1228,13 @@ More information on https://pkg.go.dev/golang.org/x/text/language
Usage: bcp47_language_tag
BIC (SWIFT code)
This validates that a string value is a valid Business Identifier Code (SWIFT code), defined in ISO 9362.
More information on https://www.iso.org/standard/60390.html
Usage: bic
TimeZone
This validates that a string value is a valid time zone based on the time zone database present on the system.
Expand Down
2 changes: 2 additions & 0 deletions regexes.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ const (
hTMLEncodedRegexString = `&#[x]?([0-9a-fA-F]{2})|(&gt)|(&lt)|(&quot)|(&amp)+[;]?`
hTMLRegexString = `<[/]?([a-zA-Z]+).*?>`
splitParamsRegexString = `'[^']*'|\S+`
bicRegexString = `^[A-Za-z]{6}[A-Za-z0-9]{2}([A-Za-z0-9]{3})?$`
)

var (
Expand Down Expand Up @@ -98,4 +99,5 @@ var (
hTMLEncodedRegex = regexp.MustCompile(hTMLEncodedRegexString)
hTMLRegex = regexp.MustCompile(hTMLRegexString)
splitParamsRegex = regexp.MustCompile(splitParamsRegexString)
bicRegex = regexp.MustCompile(bicRegexString)
)
27 changes: 27 additions & 0 deletions validator_instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,33 @@ func (v *Validate) SetTagName(name string) {
v.tagName = name
}

// ValidateMapCtx validates a map using a map of validation rules and allows passing of contextual
// validation validation information via context.Context.
func (v Validate) ValidateMapCtx(ctx context.Context, data map[string]interface{}, rules map[string]interface{}) map[string]interface{} {
errs := make(map[string]interface{})
for field, rule := range rules {
if reflect.ValueOf(rule).Kind() == reflect.Map && reflect.ValueOf(data[field]).Kind() == reflect.Map {
err := v.ValidateMapCtx(ctx, data[field].(map[string]interface{}), rule.(map[string]interface{}))
if len(err) > 0 {
errs[field] = err
}
} else if reflect.ValueOf(rule).Kind() == reflect.Map {
errs[field] = errors.New("The field: '" + field + "' is not a map to dive")
} else {
err := v.VarCtx(ctx, data[field], rule.(string))
if err != nil {
errs[field] = err
}
}
}
return errs
}

// ValidateMap validates map data form a map of tags
func (v *Validate) ValidateMap(data map[string]interface{}, rules map[string]interface{}) map[string]interface{} {
return v.ValidateMapCtx(context.Background(), data, rules)
}

// RegisterTagNameFunc registers a function to get alternate names for StructFields.
//
// eg. to use the names which have been specified for JSON representations of structs, rather than normal Go field names:
Expand Down
Loading

0 comments on commit d08f919

Please sign in to comment.