go-ozzo / ozzo-validation

An idiomatic Go (golang) validation package. Supports configurable and extensible validation rules (validators) using normal language constructs instead of error-prone struct tags.
MIT License
3.73k stars 224 forks source link

validation rule based on the value of another field #90

Closed cuotos closed 4 years ago

cuotos commented 4 years ago

Is it possible to validate one field depending on the value of a different field?

I have a field called "action", if it holds the value "create", I want a different field to be Required. But if "action" is "delete" then the other field is allowed to be empty.

cuotos commented 4 years ago

I got this working by creating a validation function and wrapping that in validation.By() and adding this to the "manifest" fields validation rules.

    requireManifestForCreateAction := func(v interface{}) error {
        if e.Action == "create" {
            return validation.Validate(v, validation.Required)
        }
        return nil
    }