Perform context-aware validation
masterSome validation rules depend dynamically on a context. To use them, implement the validation.RuleWithContext interface.
To validate an arbitrary value with a context, use validation.ValidateWithContext(). The context.Context parameter is passed to rules implementing validation.RuleWithContext. If a rule only implements validation.Rule, that standard implementation is used instead.
To validate struct fields with a context, use validation.ValidateStructWithContext().
You can convert a function into a context-aware rule using validation.WithContext().
rule := validation.WithContext(func(ctx context.Context, value interface{}) error {
if ctx.Value("secret") == value.(string) {
return nil
}
return errors.New("value incorrect")
})
value := "xyz"
ctx := context.WithValue(context.Background(), "secret", "example")
err := validation.ValidateWithContext(ctx, value, rule)
fmt.Println(err)
// Output: value incorrect