minor speed improvements

* added check for "-" in custom field name
pull/190/head
joeybloggs 9 years ago
parent 344bcd6e10
commit 3cef97a452
  1. 10
      validator.go
  2. 9
      validator_test.go

@ -404,6 +404,7 @@ func (v *Validate) tranverseStruct(topStruct reflect.Value, currentStruct reflec
numFields := current.NumField() numFields := current.NumField()
var fld reflect.StructField var fld reflect.StructField
var customName string
for i := 0; i < numFields; i++ { for i := 0; i < numFields; i++ {
fld = typ.Field(i) fld = typ.Field(i)
@ -421,10 +422,13 @@ func (v *Validate) tranverseStruct(topStruct reflect.Value, currentStruct reflec
} }
} }
customName := fld.Name customName = fld.Name
if v.fieldNameTag != "" { if v.fieldNameTag != "" {
name := strings.Split(fld.Tag.Get(v.fieldNameTag), ",")[0]
if name != "" { name := strings.SplitN(fld.Tag.Get(v.fieldNameTag), ",", 2)[0]
// dash check is for json "-" means don't output in json
if name != "" && name != "-" {
customName = name customName = name
} }
} }

@ -4936,15 +4936,24 @@ func TestCustomFieldName(t *testing.T) {
B string `schema:"b" validate:"required"` B string `schema:"b" validate:"required"`
C string `schema:"c" validate:"required"` C string `schema:"c" validate:"required"`
D []bool `schema:"d" validate:"required"` D []bool `schema:"d" validate:"required"`
E string `schema:"-" validate:"required"`
} }
a := &A{} a := &A{}
errs := New(&Config{TagName: "validate", FieldNameTag: "schema"}).Struct(a).(ValidationErrors) errs := New(&Config{TagName: "validate", FieldNameTag: "schema"}).Struct(a).(ValidationErrors)
NotEqual(t, errs, nil)
Equal(t, len(errs), 4)
Equal(t, errs["A.B"].Name, "b") Equal(t, errs["A.B"].Name, "b")
Equal(t, errs["A.C"].Name, "c") Equal(t, errs["A.C"].Name, "c")
Equal(t, errs["A.D"].Name, "d") Equal(t, errs["A.D"].Name, "d")
Equal(t, errs["A.E"].Name, "E")
errs = New(&Config{TagName: "validate"}).Struct(a).(ValidationErrors) errs = New(&Config{TagName: "validate"}).Struct(a).(ValidationErrors)
NotEqual(t, errs, nil)
Equal(t, len(errs), 4)
Equal(t, errs["A.B"].Name, "B") Equal(t, errs["A.B"].Name, "B")
Equal(t, errs["A.C"].Name, "C")
Equal(t, errs["A.D"].Name, "D")
Equal(t, errs["A.E"].Name, "E")
} }

Loading…
Cancel
Save