Giter Club home page Giter Club logo

Comments (14)

krak3n avatar krak3n commented on July 17, 2024 2

@asaskevich sure, I'll try and do it over the weekend 😃

from govalidator.

krak3n avatar krak3n commented on July 17, 2024 1

We wanted the same thing, we ended up using reflect to get the validation subject struct fields, extract their json tags to get the field name we want to return in responses, something like this:

func ValidationError(ctx echo.Context, s interface{}, err error) error {
    switch err.(type) {
    case govalidator.Errors:
        // Use reflect to get the raw struct element
        typ := reflect.TypeOf(s).Elem()
        if typ.Kind() != reflect.Struct {
            return UnexpectedError(ctx, errors.New("validation subject is not a struct"))
        }

        // This is will contain the errors we return back to user
        errs := map[string]string{}
        // Errors found by the validator
        errsByField := govalidator.ErrorsByField(err.(govalidator.Errors))
        // Loop over our struct fields
        for i := 0; i < typ.NumField(); i++ {
            // Get the field
            f := typ.Field(i)
            // Do we have an error for the field
            e, ok := errsByField[f.Name]
            if ok {
                // Try and get the `json` struct tag
                name := strings.Split(f.Tag.Get("json"), ",")[0]
                // If the name is - we should ignore the field
                if name == "-" {
                    continue
                }
                // If the name is not blank we add it our error map
                if name != "" {
                    errs[name] = e
                    continue
                }
                // Finall if all else has failed just add the raw field name to the
                // error map
                errs[f.Name] = e
            }
        }

        // Return the validation error
        mapper := &Errors{Message: "Validation Error", Errors: errs}
        return ErrorHandler(422, mapper, ctx)
    }

    // If the error type is not a govalidator.Errors, return a 500
    return UnexpectedError(
        ctx,
        fmt.Errorf("Expected govalidator.Errors, got %s", reflect.TypeOf(err)))
}

from govalidator.

asaskevich avatar asaskevich commented on July 17, 2024 1

@krak3n could you put your example into pull request with sample of usage and small note in docs please?

from govalidator.

kidtronnix avatar kidtronnix commented on July 17, 2024

+1!!!!

from govalidator.

waltton avatar waltton commented on July 17, 2024

If the intent is make the messages more user friendly I think that would be better use a field for these only purpose.

from govalidator.

kidtronnix avatar kidtronnix commented on July 17, 2024

Hmmm i see your point and in some ways it is more flexible. But also the the json tag is what the user will practically see for any restful JSON applications, which I believe will be a alot of use cases.

Could we potentially have some way of specifying a custom tag field?

from govalidator.

paroxp avatar paroxp commented on July 17, 2024

Looking forward to this PR.

Is it just going to use the json:"value" as it's field name, or perhaps different approach will be taken?

Thanks.

from govalidator.

krak3n avatar krak3n commented on July 17, 2024

@paroxp I didn't get to it last weekend but hopefully this weekend, it's just going to be documentation how how you could use reflection to get the json, xml or what ever other struct tag to get the field name you want to use for the error value.

from govalidator.

IAD avatar IAD commented on July 17, 2024

do we have updates or solution?

from govalidator.

retr0h avatar retr0h commented on July 17, 2024

What about nested field names?

If we validate the following, we get Name: invalid_alphanum does not validate as alphanum. However, we cannot identify which failed when nested fields contain the same name.

type Resource struct {
    Name string `json:"name" valid:"alphanum"`
    Version string `json:"version" valid:"required"`
    Env struct {
        Name string `json:"name" valid:"alphanum"`
        Value string `json:"value" valid:"required"`
    }
}

from govalidator.

asaskevich avatar asaskevich commented on July 17, 2024

@retr0h it should return something like Env.Name: invalid_alphanum does not validate as alphanum or Env.name ...?

from govalidator.

saifabid avatar saifabid commented on July 17, 2024

^ Yes, that would be the expected behavior, however is not the case currently

from govalidator.

saifabid avatar saifabid commented on July 17, 2024

@asaskevich *

from govalidator.

sergeyglazyrindev avatar sergeyglazyrindev commented on July 17, 2024

Hello guys!
I forked this package cause owner disappeared. Hope, he will be back, but it would be easier to merge these changes back if he is back
Link to my repo: create issue there and we'll discuss it.

from govalidator.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.