Skip to content

Allow using tags in StructFiltered #661

@masterada

Description

@masterada

Package version eg. v8, v9:

v10

Issue, Question or Enhancement:

It would be nice if there was a version of StructFiltered, where we can use tags instead of field values. It would be best to pass in a type similar to FieldError, instead of ns []byte.

Code sample, to showcase or reproduce:

func TestTest(t *testing.T) {
	v := validator.New()

	v.RegisterTagNameFunc(func(field reflect.StructField) string {
		name := strings.SplitN(field.Tag.Get("json"), ",", 2)[0]
		if name != "" && name != "-" {
			return name
		}

		return ""
	})

	type TestStruct struct {
		TestedField    string `json:"tested_field" validate:"required"`
		NotTestedField string `json:"not_tested_field" validate:"required"`
	}

	testVal := &TestStruct{
		TestedField:    "test",
		NotTestedField: "",
	}

	err := v.StructFiltered2(testVal, func(meta validator.FieldMeta) bool {
		return meta.Field() == "not_tested_field"
	})
	if err != nil {
		t.Error(err)
	}
}

Background

We use validator for a rest api. We allow partial updates to our entities. We do this by unmarshalling the incoming data to a struct, and also to a map[string]interface{}. This way we have the sent-in keys in the map, and use it to apply the incoming changes to our existing data.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions