Skip to content

Missing FieldError.Field() and 'Key' in ValidationErrors Returned from Var() and ValidateMap() #1298

Open
@neiljpowell

Description

@neiljpowell
  • [ x] I have looked at the documentation here first?
  • [ x] I have looked at the examples provided that may showcase my question here?

Package version eg. v9, v10:

v10

Issue, Question or Enhancement:

Issue: The FieldError.Field() is empty and not populating the ValidationErrors key for Error(). Consistent ValidationError messages and translation are important and should be a priority to implement. Allowing a field name/key to be passed as a argument to Var() and ValidateMap() would be great. It would also eliminate a lot of unnecessary structs added to code just for producing proper error messages.

There several Issues reported already #425 #805 #894 #1284 and at least one PR #962 to fix.

Code sample, to showcase or reproduce:

func TestValidator_VarAndMapValidationErrors(t *testing.T) {

	validtr := validator.New()
	testVar := ""
	//test validation failure
	err := validtr.Var(testVar, "required")
	for _, fieldError := range err.(validator.ValidationErrors) {
		t.Logf("Var - Name: '%s', Tag: '%s'", fieldError.Field(), fieldError.Tag())
		t.Logf("Var - Error: '%s'", fieldError.Error())
	}
	//Output:
	// Var - Name: '', Tag: 'required'
	// Var - Error: 'Key: '' Error:Field validation for '' failed on the 'required' tag'

	var testData = map[string]interface{}{"testVar": testVar}
	var testRules = map[string]interface{}{"testVar": "required"}

	errs := validtr.ValidateMap(testData, testRules)
	for _, err := range errs {
		for _, fieldError := range err.(validator.ValidationErrors) {
			t.Logf("Map - Name: '%s', Tag: '%s'", fieldError.Field(), fieldError.Tag())
			t.Logf("Map - Error: '%s'", fieldError.Error())
		}
	}
	//Output:
	// Map - Name: '', Tag: 'required'
	// Map - Error: 'Key: '' Error:Field validation for '' failed on the 'required' tag'
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions