go-playground / validator

:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving
MIT License
16.56k stars 1.31k forks source link

Remove struct name from validation error messages? #633

Open xeoncross opened 4 years ago

xeoncross commented 4 years ago

Package version: 10

Using the current translation, the struct name is included with validation error messages

trans, _ := uni.GetTranslator("en")
fields := errs.Translate(trans)

{
    enc := json.NewEncoder(os.Stderr)
    enc.SetIndent("", "  ")
    enc.Encode(fields)
}

Result:

{
  "User.Email": "Email must be a valid email address",
  "User.FirstName": "FirstName is a required field"
}

Is there a way to change this to only show field names? Here is an example.

{
  "Email": "Email must be a valid email address",
  "FirstName": "FirstName is a required field"
}

The reason is because I'm reading from a http.Request and the client does not provide the struct name, that is known only internally. This example is pulled from https://github.com/go-playground/validator/blob/master/_examples/struct-level/

xeoncross commented 4 years ago

I see that PR #305 already attempted to address this. As mentioned in that PR, only the top-level struct name should be hidden because the client does not need to know what it is called neither does the client provide it.

My current workaround is used manually removing the first entity name from all top-level fields:

func removeTopStruct(fields map[string]string) map[string]string {
    res := map[string]string{}
    for field, err := range fields {
        res[field[strings.Index(field, ".")+1:]] = err
    }
    return res
}
trans, _ := uni.GetTranslator("en")
fields := removeTopStruct(errs.Translate(trans))

{
    enc := json.NewEncoder(os.Stderr)
    enc.SetIndent("", "  ")
    enc.Encode(fields)
}
{
  "Email": "Email must be a valid email address",
  "FirstName": "FirstName is a required field"
}
suciuvlad commented 3 years ago

+1