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

failed ltfield tag with nil fields #972

Open DarkReduX opened 2 years ago

DarkReduX commented 2 years ago

Package version eg. v10:

Issue, Question or Enhancement:

Got fail on validate:"ltfield" tag when use pointers on struct fields and one of them is nil

Code sample, to showcase or reproduce:

package main

import (
    "github.com/go-playground/validator/v10"
    "github.com/google/uuid"
    "log"
)

type Test struct {
    A *int `json:"a"`
    B *int `validate:"ltefield=A"`
}

func main() {
// output:Key: 'Test.B' Error:Field validation for 'B' failed on the ' ltefield' tag
    log.Print(validator.New().Struct(&Test{
        A: nil,
        B: func(i int) *int { return &i }(10),
    }))
}
micronull commented 11 months ago

Up. ran into the same problem.

micronull commented 11 months ago

My temp resolve:


func omitnilLtefield(fl validator.FieldLevel) bool {
    f := fl.Field()
    f2 := fl.Parent().FieldByName(fl.Param())

    if f2.Kind() == reflect.Pointer && f2.IsNil() || f.IsZero() || f2.IsZero() {
        return true
    }

    switch f.Kind() { //nolint:exhaustive
    case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
        return f.Int() <= f2.Elem().Int()
    case reflect.Float32, reflect.Float64:
        return f.Float() <= f2.Elem().Float()
    }

    return true
}

validate.RegisterValidation("omitnil_ltefield", omitnilLtefield)