Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,16 @@ type StructLevel struct {
v *Validate
}

// ReportValidationErrors accepts the key relative to the top level struct and validatin errors.
// Example: had a triple nested struct User, ContactInfo, Country and ran errs := validate.Struct(country)
// from within a User struct level validation would call this method like so:
// ReportValidationErrors("ContactInfo.", errs)
func (sl *StructLevel) ReportValidationErrors(relativeKey string, errs ValidationErrors) {
for _, e := range errs {
sl.errs[sl.errPrefix+relativeKey+e.Field] = e
}
}

// ReportError reports an error just by passing the field and tag information
// NOTE: tag can be an existing validation tag or just something you make up
// and precess on the flip side it's up to you.
Expand Down
54 changes: 54 additions & 0 deletions validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,60 @@ func StructValidationTestStructInvalid(v *Validate, structLevel *StructLevel) {
}
}

func StructValidationTestStructReturnValidationErrors(v *Validate, structLevel *StructLevel) {

s := structLevel.CurrentStruct.Interface().(TestStructReturnValidationErrors)

errs := v.Struct(s.Inner1.Inner2)
if errs == nil {
return
}

structLevel.ReportValidationErrors("Inner1.", errs.(ValidationErrors))
}

type TestStructReturnValidationErrorsInner2 struct {
String string `validate:"required"`
}

type TestStructReturnValidationErrorsInner1 struct {
Inner2 *TestStructReturnValidationErrorsInner2
}

type TestStructReturnValidationErrors struct {
Inner1 *TestStructReturnValidationErrorsInner1
}

func TestStructLevelReturnValidationErrors(t *testing.T) {
config := &Config{
TagName: "validate",
}

v1 := New(config)
v1.RegisterStructValidation(StructValidationTestStructReturnValidationErrors, TestStructReturnValidationErrors{})

inner2 := &TestStructReturnValidationErrorsInner2{
String: "I'm HERE",
}

inner1 := &TestStructReturnValidationErrorsInner1{
Inner2: inner2,
}

val := &TestStructReturnValidationErrors{
Inner1: inner1,
}

errs := v1.Struct(val)
Equal(t, errs, nil)

inner2.String = ""

errs = v1.Struct(val)
NotEqual(t, errs, nil)
AssertError(t, errs, "TestStructReturnValidationErrors.Inner1.Inner2.String", "String", "required")
}

func TestStructLevelValidations(t *testing.T) {

config := &Config{
Expand Down