validator

package
v1.75.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 13, 2023 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package validator wraps https://github.com/go-playground/validator to provide value validations for structs and individual fields based on tags. It includes a simpler custom translation mechanism for errors.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func CustomValidationTags

func CustomValidationTags() map[string]vt.FuncCtx

CustomValidationTags returns a map of custom tags with validation function.

func ErrorTemplates

func ErrorTemplates() map[string]string

ErrorTemplates returns a map of validation tags with error messages as html templates.

Types

type Error

type Error struct {
	// Tag is the validation tag that failed (e.g. "max").
	Tag string

	// Param is the Tag's parameter value (if any - e.g. "10").
	Param string

	// FullTag is the validation tag that failed with included parameters (e.g. "max=10").
	FullTag string

	// Namespace for the field error, with the tag name taking precedence over the field's actual name.
	Namespace string

	// StructNamespace is the namespace for the field error, with the field's actual name.
	StructNamespace string

	// Field is the field name with the tag name taking precedence over the field's actual name.
	Field string

	// StructField is the field's actual name from the struct.
	StructField string

	// Kind is the Field's string representation of the kind (e.g. Int,Slice,...).
	Kind string

	// Value is the actual field's value.
	Value any

	// Err is the translated error message.
	Err string
}

Error is a custom error adding a Field member.

func (*Error) Error

func (e *Error) Error() string

Error returns a string representation of the error.

type Option

type Option func(v *Validator) error

Option is the interface that allows to set configuration options.

func WithCustomTypeFunc added in v1.66.0

func WithCustomTypeFunc(fn vt.CustomTypeFunc, types ...any) Option

WithCustomTypeFunc registers a CustomTypeFunc against a number of types.

func WithCustomValidationTags

func WithCustomValidationTags(t map[string]vt.FuncCtx) Option

WithCustomValidationTags register custom tags and validation functions.

func WithErrorTemplates

func WithErrorTemplates(t map[string]string) Option

WithErrorTemplates sets basic template-based error message translations. The argument t maps tags to html templates that uses the Error data. These translations takes precedence over the parent library translation object.

func WithFieldNameTag

func WithFieldNameTag(tag string) Option

WithFieldNameTag allows to use the field names specified by the tag instead of the original struct names.

type Validator

type Validator struct {
	// contains filtered or unexported fields
}

Validator contains the validator object fields.

func New

func New(opts ...Option) (*Validator, error)

New returns a new validator with the specified options.

func (*Validator) ValidateStruct

func (v *Validator) ValidateStruct(obj any) error

ValidateStruct validates the structure fields tagged with "validate" and returns a multierror.

Example
package main

import (
	"fmt"
	"log"

	"github.com/Vonage/gosrvlib/pkg/validator"
)

const (
	// fieldTagName is the name of the tag used for the validator rules.
	fieldTagName = "json"
)

// SubStruct is an example structure type used to test nested structures.
type SubStruct struct {
	URLField string `json:"sub_string" validate:"required,url"`
	IntField int    `json:"sub_int" validate:"required,min=2"`
}

// RootStruct is an example structure type.
type RootStruct struct {
	BoolField   bool       `json:"bool_field"`
	SubStr      SubStruct  `json:"sub_struct" validate:"required"`
	SubStrPtr   *SubStruct `json:"sub_struct_ptr" validate:"required"`
	StringField string     `json:"string_field" validate:"required"`
	NoNameField string     `json:"-" validate:"required"`
}

func main() {
	// data structure to check
	validObj := RootStruct{
		BoolField: true,
		SubStr: SubStruct{
			URLField: "http://first.test.invalid",
			IntField: 3,
		},
		SubStrPtr: &SubStruct{
			URLField: "http://second.test.invalid",
			IntField: 123,
		},
		StringField: "hello world",
		NoNameField: "test",
	}

	// instantiate the validator object
	v, err := validator.New(
		validator.WithFieldNameTag(fieldTagName),
		validator.WithCustomValidationTags(validator.CustomValidationTags()),
		validator.WithErrorTemplates(validator.ErrorTemplates()),
	)
	if err != nil {
		log.Fatal(err)
	}

	// check the data structure
	err = v.ValidateStruct(validObj)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("OK")

}
Output:

OK

func (*Validator) ValidateStructCtx

func (v *Validator) ValidateStructCtx(ctx context.Context, obj any) error

ValidateStructCtx validates the structure fields tagged with "validate" and returns a multierror.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL