asaskevich / govalidator

[Go] Package of validators and sanitizers for strings, numerics, slices and structs
MIT License
6.02k stars 556 forks source link

null tag: support integers #376

Closed hazcod closed 3 years ago

hazcod commented 4 years ago

Hi, for my API endpoint I need to make sure that people do not try to use their own primary keys. This is done via:

type Custom struct {
    Id          uint32      `pg:"id,pk" json:"id" validate:"null"`
}

But this still goes through if I post with {"id":1}

msiner commented 3 years ago

The tag name is incorrect. Instead of "validate" it needs to be "valid". I believe the example below shows the behavior you are expecting.

type Custom struct {
    Id uint32 `pg:"id,pk" json:"id" valid:"null"`
}

func main() {
    x := Custom{Id: 1}
    ok, err := govalidator.ValidateStruct(x)
    fmt.Println(ok, err)
    y := Custom{}
    ok, err = govalidator.ValidateStruct(y)
    fmt.Println(ok, err)
}

Output:

false id: 1 does not validate as null
true <nil>