I'm attempting to register custom validation for a struct using go-playgrounds validator package.
The problem I'm having is that the custom validator function I register isn't being called for the embedded struct.
Here is a complete working example: https://play.golang.org/p/r7oaSo890q_L
So, how do I run struct level validations on an embedded struct?
EDIT*
Just to be specific - I don't want to use general struct validation, as I want to have multiple tags for the same type.
What I mean is that using:
validator.RegisterStructValidation(SomeFunc, decimal.Decimal)
won't work for me as I want the flexibility of having multiple tags for the same type. Sometimes I want the decimal to be pos, sometimes neg etc
EDIT2* Here is the code in the link:
package main
import (
"fmt"
"github.com/shopspring/decimal"
"gopkg.in/go-playground/validator.v9"
)
type decimalPosRequest struct {
MoneyAmount decimal.Decimal `validate:"decimalpos"` // trying to validate this
}
func main() {
val := validator.New()
val.RegisterValidation(`decimalpos`,ValidateDecimalPositive)
request := decimalPosRequest{MoneyAmount: decimal.NewFromFloat(-1.0)}
err := val.Struct(&request)
if err == nil {
fmt.Println("Error! Should have failed but didn't")
}
}
func ValidateDecimalPositive(fl validator.FieldLevel) bool { // this function is never called for some reason
// get decimal
value := fl.Field().Interface().(decimal.Decimal)
// check is positive
return value.IsPositive()
}
It looks like validator skip over types that are not registered. We'd have to register the type before registering a custom validation function.
Here's how you could do it: https://go.dev/play/p/o7HrSTGFDxt
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.