go-playground / validator

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

How to implement group validator? #846

Open nogolang opened 3 years ago

nogolang commented 3 years ago

How to implement group validator?

I have the following structure

type User struct {
    UserId        int64          `binding:"required,number"`
    Name         string         `json:"name" form:"name" binding:"gte=3"`
}

Now I need to implement findUserById , I have to verify the ID exist, so i use required. But when I implement saveUser, I have to verify that the ID doesn't exist because my database is a self-increment ID. They have a conflict

image

In Java spring boot, they can be distinguished by a custom group

deankarn commented 3 years ago

The honest answer would be to break your Find + Save User struct up into two separate ones. I highly recommend doing this regardless otherwise you'll eventually end up with abstraction leakage between the two use case resulting in less maintainable and more brittle code.

I can't see adding this sort of grouping functionality support.

Hope this helps answer the question.