Documentation ¶
Overview ¶
Example ¶
person := &pb.Person{ Id: 1234, Email: "protovalidate@buf.build", Name: "Buf Build", Home: &pb.Coordinates{ Lat: 27.380583333333334, Lng: 33.631838888888886, }, } err := Validate(person) fmt.Println("valid:", err) person.Email = "not an email" err = Validate(person) fmt.Println("invalid:", err)
Output: valid: <nil> invalid: validation error: - email: value must be a valid email address [string.email]
Index ¶
- func FieldPathString(path *validate.FieldPath) string
- func Validate(msg proto.Message) error
- type CompilationError
- type RuntimeError
- type StandardConstraintInterceptor
- type StandardConstraintResolver
- type ValidationError
- type Validator
- type ValidatorOption
- func WithAllowUnknownFields(allowUnknownFields bool) ValidatorOption
- func WithDescriptors(descriptors ...protoreflect.MessageDescriptor) ValidatorOption
- func WithDisableLazy(disable bool) ValidatorOption
- func WithExtensionTypeResolver(extensionTypeResolver protoregistry.ExtensionTypeResolver) ValidatorOption
- func WithFailFast(failFast bool) ValidatorOption
- func WithMessages(messages ...proto.Message) ValidatorOption
- func WithStandardConstraintInterceptor(interceptor StandardConstraintInterceptor) ValidatorOption
- func WithUTC(useUTC bool) ValidatorOption
- type Violation
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func FieldPathString ¶ added in v0.8.0
FieldPathString returns a dotted path string for the provided validate.FieldPath.
func Validate ¶ added in v0.7.2
Validate uses a global instance of Validator constructed with no ValidatorOptions and calls its Validate function. For the vast majority of validation cases, using this global function is safe and acceptable. If you need to provide i.e. a custom ExtensionTypeResolver, you'll need to construct a Validator.
Types ¶
type CompilationError ¶
type CompilationError = errors.CompilationError
A CompilationError is returned if a CEL expression cannot be compiled & type-checked or if invalid standard constraints are applied to a field.
type RuntimeError ¶
type RuntimeError = errors.RuntimeError
A RuntimeError is returned if a valid CEL expression evaluation is terminated, typically due to an unknown or mismatched type.
type StandardConstraintInterceptor ¶
type StandardConstraintInterceptor func(res StandardConstraintResolver) StandardConstraintResolver
StandardConstraintInterceptor can be provided to WithStandardConstraintInterceptor to allow modifying a StandardConstraintResolver.
type StandardConstraintResolver ¶
type StandardConstraintResolver interface { ResolveMessageConstraints(desc protoreflect.MessageDescriptor) *validate.MessageConstraints ResolveOneofConstraints(desc protoreflect.OneofDescriptor) *validate.OneofConstraints ResolveFieldConstraints(desc protoreflect.FieldDescriptor) *validate.FieldConstraints }
StandardConstraintResolver is responsible for resolving the standard constraints from the provided protoreflect.Descriptor. The default resolver can be intercepted and modified using WithStandardConstraintInterceptor.
type ValidationError ¶
type ValidationError = errors.ValidationError
ValidationError is returned if one or more constraints on a message are violated. This error type is a composite of multiple Violation instances.
err = validator.Validate(msg) var valErr *ValidationError if ok := errors.As(err, &valErr); ok { violations := valErrs.Violations // ... }
Example ¶
validator, err := New() if err != nil { log.Fatal(err) } loc := &pb.Coordinates{Lat: 999.999} err = validator.Validate(loc) var valErr *ValidationError if ok := errors.As(err, &valErr); ok { violation := valErr.Violations[0] fmt.Println(FieldPathString(violation.Proto.GetField()), violation.Proto.GetConstraintId()) fmt.Println(violation.RuleValue, violation.FieldValue) }
Output: lat double.gte_lte -90 999.999
Example (Localized) ¶
validator, err := New() if err != nil { log.Fatal(err) } type ErrorInfo struct { FieldName string RuleValue any FieldValue any } var ruleMessages = map[string]string{ "string.email_empty": "{{.FieldName}}: メールアドレスは空であってはなりません。\n", "string.pattern": "{{.FieldName}}: 値はパターン「{{.RuleValue}}」一致する必要があります。\n", "uint64.gt": "{{.FieldName}}: 値は{{.RuleValue}}を超える必要があります。(価値:{{.FieldValue}})\n", } loc := &pb.Person{Id: 900} err = validator.Validate(loc) var valErr *ValidationError if ok := errors.As(err, &valErr); ok { for _, violation := range valErr.Violations { _ = template. Must(template.New("").Parse(ruleMessages[violation.Proto.GetConstraintId()])). Execute(os.Stdout, ErrorInfo{ FieldName: FieldPathString(violation.Proto.GetField()), RuleValue: violation.RuleValue.Interface(), FieldValue: violation.FieldValue.Interface(), }) } }
Output: id: 値は999を超える必要があります。(価値:900) email: メールアドレスは空であってはなりません。 name: 値はパターン「^[[:alpha:]]+( [[:alpha:]]+)*$」一致する必要があります。
type Validator ¶
type Validator struct {
// contains filtered or unexported fields
}
Validator performs validation on any proto.Message values. The Validator is safe for concurrent use.
func New ¶
func New(options ...ValidatorOption) (*Validator, error)
New creates a Validator with the given options. An error may occur in setting up the CEL execution environment if the configuration is invalid. See the individual ValidatorOption for how they impact the fallibility of New.
func (*Validator) Validate ¶
Validate checks that message satisfies its constraints. Constraints are defined within the Protobuf file as options from the buf.validate package. An error is returned if the constraints are violated (ValidationError), the evaluation logic for the message cannot be built (CompilationError), or there is a type error when attempting to evaluate a CEL expression associated with the message (RuntimeError).
type ValidatorOption ¶
type ValidatorOption func(*config)
A ValidatorOption modifies the default configuration of a Validator. See the individual options for their defaults and affects on the fallibility of configuring a Validator.
func WithAllowUnknownFields ¶ added in v0.7.0
func WithAllowUnknownFields(allowUnknownFields bool) ValidatorOption
WithAllowUnknownFields specifies if the presence of unknown field constraints should cause compilation to fail with an error. When set to false, an unknown field will simply be ignored, which will cause constraints to silently not be applied. This condition may occur if a predefined constraint definition isn't present in the extension type resolver, or when passing dynamic messages with standard constraints defined in a newer version of protovalidate. The default value is false, to prevent silently-incorrect validation from occurring.
func WithDescriptors ¶
func WithDescriptors(descriptors ...protoreflect.MessageDescriptor) ValidatorOption
WithDescriptors allows warming up the Validator with message descriptors that are expected to be validated. Messages included transitively (i.e., fields with message values) are automatically handled.
Example ¶
pbType, err := protoregistry.GlobalTypes.FindMessageByName("tests.example.v1.Person") if err != nil { log.Fatal(err) } validator, err := New( WithDescriptors( pbType.Descriptor(), ), ) if err != nil { log.Fatal(err) } person := &pb.Person{ Id: 1234, Email: "protovalidate@buf.build", Name: "Protocol Buffer", } err = validator.Validate(person) fmt.Println(err)
Output: <nil>
func WithDisableLazy ¶
func WithDisableLazy(disable bool) ValidatorOption
WithDisableLazy prevents the Validator from lazily building validation logic for a message it has not encountered before. Disabling lazy logic additionally eliminates any internal locking as the validator becomes read-only.
Note: All expected messages must be provided by WithMessages or WithDescriptors during initialization.
Example ¶
person := &pb.Person{ Id: 1234, Email: "protovalidate@buf.build", Name: "Buf Build", Home: &pb.Coordinates{ Lat: 27.380583333333334, Lng: 33.631838888888886, }, } validator, err := New( WithMessages(&pb.Coordinates{}), WithDisableLazy(true), ) if err != nil { log.Fatal(err) } err = validator.Validate(person.GetHome()) fmt.Println("person.Home:", err) err = validator.Validate(person) fmt.Println("person:", err)
Output: person.Home: <nil> person: compilation error: no evaluator available for tests.example.v1.Person
func WithExtensionTypeResolver ¶ added in v0.7.0
func WithExtensionTypeResolver(extensionTypeResolver protoregistry.ExtensionTypeResolver) ValidatorOption
WithExtensionTypeResolver specifies a resolver to use when reparsing unknown extension types. When dealing with dynamic file descriptor sets, passing this option will allow extensions to be resolved using a custom resolver.
To ignore unknown extension fields, use the WithAllowUnknownFields option. Note that this may result in messages being treated as valid even though not all constraints are being applied.
func WithFailFast ¶
func WithFailFast(failFast bool) ValidatorOption
WithFailFast specifies whether validation should fail on the first constraint violation encountered or if all violations should be accumulated. By default, all violations are accumulated.
Example ¶
loc := &pb.Coordinates{Lat: 999.999, Lng: -999.999} validator, err := New() if err != nil { log.Fatal(err) } err = validator.Validate(loc) fmt.Println("default:", err) validator, err = New(WithFailFast(true)) if err != nil { log.Fatal(err) } err = validator.Validate(loc) fmt.Println("fail fast:", err)
Output: default: validation error: - lat: value must be greater than or equal to -90 and less than or equal to 90 [double.gte_lte] - lng: value must be greater than or equal to -180 and less than or equal to 180 [double.gte_lte] fail fast: validation error: - lat: value must be greater than or equal to -90 and less than or equal to 90 [double.gte_lte]
func WithMessages ¶
func WithMessages(messages ...proto.Message) ValidatorOption
WithMessages allows warming up the Validator with messages that are expected to be validated. Messages included transitively (i.e., fields with message values) are automatically handled.
Example ¶
validator, err := New( WithMessages(&pb.Person{}), ) if err != nil { log.Fatal(err) } person := &pb.Person{ Id: 1234, Email: "protovalidate@buf.build", Name: "Protocol Buffer", } err = validator.Validate(person) fmt.Println(err)
Output: <nil>
func WithStandardConstraintInterceptor ¶
func WithStandardConstraintInterceptor(interceptor StandardConstraintInterceptor) ValidatorOption
WithStandardConstraintInterceptor allows intercepting the StandardConstraintResolver used by the Validator to modify or replace it.
func WithUTC ¶
func WithUTC(useUTC bool) ValidatorOption
WithUTC specifies whether timestamp operations should use UTC or the OS's local timezone for timestamp related values. By default, the local timezone is used.