validation

package
v5.5.0 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2024 License: MIT Imports: 27 Imported by: 7

Documentation

Index

Constants

View Source
const (
	FieldTypeNumeric     = "numeric"
	FieldTypeString      = "string"
	FieldTypeBool        = "bool"
	FieldTypeFile        = "file"
	FieldTypeArray       = "array"
	FieldTypeObject      = "object"
	FieldTypeUnsupported = "unsupported"
)

FieldType returned by the GetFieldType function.

View Source
const (
	// CurrentElement special key for field name in composite rule sets.
	// Use it if you want to apply rules to the current object element.
	// You cannot apply rules on the root element, these rules will only
	// apply if the rule set is used with composition.
	CurrentElement = ""
)

Variables

View Source
var ImageMIMETypes = []string{"image/jpeg", "image/png", "image/gif", "image/bmp", "image/svg+xml", "image/webp"}

ImageMIMETypes MIME types accepted by `ImageValidator`.

Functions

func GetFieldName

func GetFieldName(lang *lang.Language, path *walk.Path) string

GetFieldName returns the localized name of the field identified by the given path.

func GetFieldType

func GetFieldType(value any) string

GetFieldType returns the non-technical type of the given "value" interface. This is used by validation rules to know if the input data is a candidate for validation or not and is especially useful for type-dependent rules.

  • "numeric" (`lang.FieldTypeNumeric`) if the value is an int, uint or a float
  • "string" (`lang.FieldTypeString`) if the value is a string
  • "array" (`lang.FieldTypeArray`) if the value is a slice
  • "file" (`lang.FieldTypeFile`) if the value is a slice of "fsutil.File"
  • "bool" (`lang.FieldTypeBool`) if the value is a bool
  • "unsupported" (`lang.FieldTypeUnsupported`) otherwise

Types

type AddedValidationError

type AddedValidationError[T addedValidationErrorConstraint] struct {
	Path  *walk.Path
	Error T
}

AddedValidationError a simple association path/message or path/*Errors for use in `Context.AddValidationError` or `Context.AddValidationErrors`

type AfterEqualFieldValidator

type AfterEqualFieldValidator struct {
	DateFieldComparisonValidator
}

AfterEqualFieldValidator validates the field under validation must be a date (`time.Time`) after or equal to all the other dates matched by the specified path.

func AfterEqualField

func AfterEqualField(path string) *AfterEqualFieldValidator

AfterEqualField the field under validation must be a date (`time.Time`) after or equal to the date field identified by the given path.

func (*AfterEqualFieldValidator) Config

func (c *AfterEqualFieldValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*AfterEqualFieldValidator) DB

func (c *AfterEqualFieldValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*AfterEqualFieldValidator) Lang

func (c *AfterEqualFieldValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*AfterEqualFieldValidator) Logger

func (c *AfterEqualFieldValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*AfterEqualFieldValidator) Name

func (v *AfterEqualFieldValidator) Name() string

Name returns the string name of the validator.

func (*AfterEqualFieldValidator) Validate

func (v *AfterEqualFieldValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type AfterEqualValidator

type AfterEqualValidator struct {
	DateComparisonValidator
}

AfterEqualValidator validates the field under validation must be a date (`time.Time`) after or equal to the specified date.

func AfterEqual

func AfterEqual(date time.Time) *AfterEqualValidator

AfterEqual the field under validation must be a date (`time.Time`) after or equal to the given date.

func (*AfterEqualValidator) Config

func (c *AfterEqualValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*AfterEqualValidator) DB

func (c *AfterEqualValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*AfterEqualValidator) Lang

func (c *AfterEqualValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*AfterEqualValidator) Logger

func (c *AfterEqualValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*AfterEqualValidator) Name

func (v *AfterEqualValidator) Name() string

Name returns the string name of the validator.

func (*AfterEqualValidator) Validate

func (v *AfterEqualValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type AfterFieldValidator

type AfterFieldValidator struct {
	DateFieldComparisonValidator
}

AfterFieldValidator validates the field under validation must be a date (`time.Time`) before all the other dates matched by the specified path.

func AfterField

func AfterField(path string) *AfterFieldValidator

AfterField the field under validation must be a date (`time.Time`) before the date field identified by the given path.

func (*AfterFieldValidator) Config

func (c *AfterFieldValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*AfterFieldValidator) DB

func (c *AfterFieldValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*AfterFieldValidator) Lang

func (c *AfterFieldValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*AfterFieldValidator) Logger

func (c *AfterFieldValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*AfterFieldValidator) Name

func (v *AfterFieldValidator) Name() string

Name returns the string name of the validator.

func (*AfterFieldValidator) Validate

func (v *AfterFieldValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type AfterValidator

type AfterValidator struct {
	DateComparisonValidator
}

AfterValidator validates the field under validation must be a date (`time.Time`) before the specified date.

func After

func After(date time.Time) *AfterValidator

After the field under validation must be a date (`time.Time`) before the given date.

func (*AfterValidator) Config

func (c *AfterValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*AfterValidator) DB

func (c *AfterValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*AfterValidator) Lang

func (c *AfterValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*AfterValidator) Logger

func (c *AfterValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*AfterValidator) Name

func (v *AfterValidator) Name() string

Name returns the string name of the validator.

func (*AfterValidator) Validate

func (v *AfterValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type AlphaDashValidator

type AlphaDashValidator struct {
	RegexValidator
}

AlphaDashValidator the field under validation must a string made of alphabetic-numeric characters, dashes or underscores.

func AlphaDash

func AlphaDash() *AlphaDashValidator

AlphaDash the field under validation must be a string made of alphabetic-numeric characters, dashes or underscores.

func (*AlphaDashValidator) Config

func (c *AlphaDashValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*AlphaDashValidator) DB

func (c *AlphaDashValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*AlphaDashValidator) Lang

func (c *AlphaDashValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*AlphaDashValidator) Logger

func (c *AlphaDashValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*AlphaDashValidator) Name

func (v *AlphaDashValidator) Name() string

Name returns the string name of the validator.

type AlphaNumValidator

type AlphaNumValidator struct {
	RegexValidator
}

AlphaNumValidator the field under validation must an alphabetic-numeric string.

func AlphaNum

func AlphaNum() *AlphaNumValidator

AlphaNum the field under validation must an alphabetic-numeric string.

func (*AlphaNumValidator) Config

func (c *AlphaNumValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*AlphaNumValidator) DB

func (c *AlphaNumValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*AlphaNumValidator) Lang

func (c *AlphaNumValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*AlphaNumValidator) Logger

func (c *AlphaNumValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*AlphaNumValidator) Name

func (v *AlphaNumValidator) Name() string

Name returns the string name of the validator.

type AlphaValidator

type AlphaValidator struct {
	RegexValidator
}

AlphaValidator the field under validation must be an alphabetic string.

func Alpha

func Alpha() *AlphaValidator

Alpha the field under validation must be an alphabetic string.

func (*AlphaValidator) Config

func (c *AlphaValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*AlphaValidator) DB

func (c *AlphaValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*AlphaValidator) Lang

func (c *AlphaValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*AlphaValidator) Logger

func (c *AlphaValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*AlphaValidator) Name

func (v *AlphaValidator) Name() string

Name returns the string name of the validator.

type ArrayErrors

type ArrayErrors map[int]*Errors

ArrayErrors representing the errors associated with an element of an array. The key is the index of the element in the array, or -1 if the element doesn't exist.

func (ArrayErrors) Add

func (e ArrayErrors) Add(path *walk.Path, index int, message string)

Add an error message to the element identified by the given path in the array, at the given index. "-1" index is accepted to identify non-existing elements. Creates all missing elements in the path.

func (ArrayErrors) Merge

func (e ArrayErrors) Merge(path *walk.Path, index int, errors *Errors)

Merge the given errors into this bag of errors at the given path.

type ArrayValidator

type ArrayValidator struct {
	BaseValidator
}

ArrayValidator validates the field under validation must be an array.

func Array

func Array() *ArrayValidator

Array the field under validation must be an array. On successful validation and if possible, converts the array to its correct type based on its elements' type. If all elements have the same type, the array is converted to a slice of this type.

func (*ArrayValidator) Config

func (c *ArrayValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*ArrayValidator) DB

func (c *ArrayValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*ArrayValidator) IsType

func (v *ArrayValidator) IsType() bool

IsType returns true.

func (*ArrayValidator) Lang

func (c *ArrayValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*ArrayValidator) Logger

func (c *ArrayValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*ArrayValidator) Name

func (v *ArrayValidator) Name() string

Name returns the string name of the validator.

func (*ArrayValidator) Validate

func (v *ArrayValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type BaseValidator

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

BaseValidator composable structure that implements the basic functions required to satisfy the `Validator` interface.

func (*BaseValidator) Config

func (c *BaseValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*BaseValidator) DB

func (c *BaseValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*BaseValidator) IsType

func (v *BaseValidator) IsType() bool

IsType returns false.

func (*BaseValidator) IsTypeDependent

func (v *BaseValidator) IsTypeDependent() bool

IsTypeDependent returns false.

func (*BaseValidator) Lang

func (c *BaseValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*BaseValidator) Logger

func (c *BaseValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*BaseValidator) MessagePlaceholders

func (v *BaseValidator) MessagePlaceholders(_ *Context) []string

MessagePlaceholders returns an empty slice (no placeholders)

type BeforeEqualFieldValidator

type BeforeEqualFieldValidator struct {
	DateFieldComparisonValidator
}

BeforeEqualFieldValidator validates the field under validation must be a date (`time.Time`) before or equal to all the other dates matched by the specified path.

func BeforeEqualField

func BeforeEqualField(path string) *BeforeEqualFieldValidator

BeforeEqualField the field under validation must be a date (`time.Time`) before or equal to the date field identified by the given path.

func (*BeforeEqualFieldValidator) Config

func (c *BeforeEqualFieldValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*BeforeEqualFieldValidator) DB

func (c *BeforeEqualFieldValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*BeforeEqualFieldValidator) Lang

func (c *BeforeEqualFieldValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*BeforeEqualFieldValidator) Logger

func (c *BeforeEqualFieldValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*BeforeEqualFieldValidator) Name

Name returns the string name of the validator.

func (*BeforeEqualFieldValidator) Validate

func (v *BeforeEqualFieldValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type BeforeEqualValidator

type BeforeEqualValidator struct {
	DateComparisonValidator
}

BeforeEqualValidator validates the field under validation must be a date (`time.Time`) before or equal to the specified date.

func BeforeEqual

func BeforeEqual(date time.Time) *BeforeEqualValidator

BeforeEqual the field under validation must be a date (`time.Time`) before or equal to the given date.

func (*BeforeEqualValidator) Config

func (c *BeforeEqualValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*BeforeEqualValidator) DB

func (c *BeforeEqualValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*BeforeEqualValidator) Lang

func (c *BeforeEqualValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*BeforeEqualValidator) Logger

func (c *BeforeEqualValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*BeforeEqualValidator) Name

func (v *BeforeEqualValidator) Name() string

Name returns the string name of the validator.

func (*BeforeEqualValidator) Validate

func (v *BeforeEqualValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type BeforeFieldValidator

type BeforeFieldValidator struct {
	DateFieldComparisonValidator
}

BeforeFieldValidator validates the field under validation must be a date (`time.Time`) before all the other dates matched by the specified path.

func BeforeField

func BeforeField(path string) *BeforeFieldValidator

BeforeField the field under validation must be a date (`time.Time`) before the date field identified by the given path.

func (*BeforeFieldValidator) Config

func (c *BeforeFieldValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*BeforeFieldValidator) DB

func (c *BeforeFieldValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*BeforeFieldValidator) Lang

func (c *BeforeFieldValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*BeforeFieldValidator) Logger

func (c *BeforeFieldValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*BeforeFieldValidator) Name

func (v *BeforeFieldValidator) Name() string

Name returns the string name of the validator.

func (*BeforeFieldValidator) Validate

func (v *BeforeFieldValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type BeforeValidator

type BeforeValidator struct {
	DateComparisonValidator
}

BeforeValidator validates the field under validation must be a date (`time.Time`) before the specified date.

func Before

func Before(date time.Time) *BeforeValidator

Before the field under validation must be a date (`time.Time`) before the given date.

func (*BeforeValidator) Config

func (c *BeforeValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*BeforeValidator) DB

func (c *BeforeValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*BeforeValidator) Lang

func (c *BeforeValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*BeforeValidator) Logger

func (c *BeforeValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*BeforeValidator) Name

func (v *BeforeValidator) Name() string

Name returns the string name of the validator.

func (*BeforeValidator) Validate

func (v *BeforeValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type BetweenValidator

type BetweenValidator struct {
	BaseValidator
	Min float64
	Max float64
}

BetweenValidator validates the field under validation depending on its type.

  • Numbers are directly compared if they fit in `float64`. If they don't the rule doesn't pass.
  • Strings must have a length between min and max characters (calculated based on the number of grapheme clusters)
  • Arrays must have at between min and max elements
  • Objects must have at between min and max keys
  • Files must weight between min and max KiB (for multi-files, all files must match this criteria). The number of KiB of each file is rounded up (ceil).

All comparisons are inclusive.

func Between

func Between(min, max float64) *BetweenValidator

Between validates the field under validation depending on its type.

  • Numbers are directly compared if they fit in `float64`. If they don't the rule doesn't pass.
  • Strings must have a length between min and max characters (calculated based on the number of grapheme clusters)
  • Arrays must have at between min and max elements
  • Objects must have at between min and max keys
  • Files must weight between min and max KiB (for multi-files, all files must match this criteria). The number of KiB of each file is rounded up (ceil).

All comparisons are inclusive.

func (*BetweenValidator) Config

func (c *BetweenValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*BetweenValidator) DB

func (c *BetweenValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*BetweenValidator) IsTypeDependent

func (v *BetweenValidator) IsTypeDependent() bool

IsTypeDependent returns true

func (*BetweenValidator) Lang

func (c *BetweenValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*BetweenValidator) Logger

func (c *BetweenValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*BetweenValidator) MessagePlaceholders

func (v *BetweenValidator) MessagePlaceholders(_ *Context) []string

MessagePlaceholders returns the ":min" and ":max" placeholder.

func (*BetweenValidator) Name

func (v *BetweenValidator) Name() string

Name returns the string name of the validator.

func (*BetweenValidator) Validate

func (v *BetweenValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type BoolValidator

type BoolValidator struct {
	BaseValidator
}

BoolValidator the field under validation must be a bool or one of the following values:

  • "1" / "0"
  • "true" / "false"
  • "yes" / "no"
  • "on" / "off"
  • a number different from 0 is converetd to `true`, a number equals to 0 is converted to `false`

This rule converts the field to `bool` if it passes.

func Bool

func Bool() *BoolValidator

Bool the field under validation must be a bool or one of the following values:

  • "1" / "0"
  • "true" / "false"
  • "yes" / "no"
  • "on" / "off"
  • a number different from 0 is converetd to `true`, a number equals to 0 is converted to `false`

This rule converts the field to `bool` if it passes.

func (*BoolValidator) Config

func (c *BoolValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*BoolValidator) DB

func (c *BoolValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*BoolValidator) IsType

func (v *BoolValidator) IsType() bool

IsType returns true

func (*BoolValidator) Lang

func (c *BoolValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*BoolValidator) Logger

func (c *BoolValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*BoolValidator) Name

func (v *BoolValidator) Name() string

Name returns the string name of the validator.

func (*BoolValidator) Validate

func (v *BoolValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type ComparisonValidator

type ComparisonValidator struct {
	BaseValidator
	Path *walk.Path
}

ComparisonValidator validates the field under validation is greater than field identified by the given path. Mixed types are supported, meaning you can use this rule for the following (non-exhaustive) cases:

  • Compare the length of two strings
  • Compare the value of two numeric fields
  • Compare a numeric field with the length of a string or a string length with a numeric field
  • Compare a numeric field with the number of elements in an array
  • Compare the number of keys in an object with a numeric field
  • Compare a file (or multifile) size with a numeric field. The number of KiB of each file is rounded up (ceil).

func (*ComparisonValidator) Config

func (c *ComparisonValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*ComparisonValidator) DB

func (c *ComparisonValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*ComparisonValidator) IsTypeDependent

func (v *ComparisonValidator) IsTypeDependent() bool

IsTypeDependent returns true

func (*ComparisonValidator) Lang

func (c *ComparisonValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*ComparisonValidator) Logger

func (c *ComparisonValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*ComparisonValidator) MessagePlaceholders

func (v *ComparisonValidator) MessagePlaceholders(_ *Context) []string

MessagePlaceholders returns the ":other" placeholder.

type Composable

type Composable interface {
	DB() *gorm.DB
	Config() *config.Config
	Lang() *lang.Language
	Logger() *slog.Logger
}

Composable is a partial clone of `goyave.Component`, only including the accessors necessary for validation. Validators must implement this interface so they have access to DB, Config, Language and Logger.

type Context

type Context struct {
	// Context is never nil. Defaults to `context.Background()`. Readonly.
	Context context.Context
	Data    any

	// Extra the map of Extra from the validation Options.
	Extra  map[any]any
	Value  any
	Parent any
	Field  *Field

	Now time.Time

	// The name of the field under validation
	Name string

	// Invalid is true if at least one validator prior to the current one didn't pass
	// on the field under validation. This field is readonly.
	Invalid bool
	// contains filtered or unexported fields
}

Context is a structure unique per `Validator.Validate()` execution containing all the data required by a validator.

func (*Context) AddArrayElementValidationErrors

func (c *Context) AddArrayElementValidationErrors(index ...int)

AddArrayElementValidationErrors marks a child element to the field currently under validation as invalid. This is useful when a validation rule validates an array and wants to precisely mark which element in the array is invalid.

func (*Context) AddError

func (c *Context) AddError(err ...error)

AddError adds an error to the validation context. This is NOT supposed to be used when the field under validation doesn't match the rule, but rather when there has been an operation error (such as a database error).

func (*Context) AddValidationError

func (c *Context) AddValidationError(path *walk.Path, message string)

AddValidationError add a validation error message at the given path. The path is relative to the root element.

This can be used when a validation rule uses nested validation or needs to add a message on another field than the one this validator is targeted at.

func (*Context) AddValidationErrors

func (c *Context) AddValidationErrors(path *walk.Path, errors *Errors)

AddValidationErrors add a `*Errors` to be merged into the errors bag of the current validation. The path is relative to the root element.

This can be used when a validation rule uses nested validation needs to merge the results into the higher-level validation errors.

See `*validation.Errors.Merge` for more details.

func (*Context) AddedValidationError

func (c *Context) AddedValidationError() []AddedValidationError[string]

AddedValidationError returns the additional errors added with `AddValidationError`.

func (*Context) AddedValidationErrors

func (c *Context) AddedValidationErrors() []AddedValidationError[*Errors]

AddedValidationErrors returns the additional errors added with `AddValidationErrors`.

func (*Context) ArrayElementErrors

func (c *Context) ArrayElementErrors() []int

ArrayElementErrors returns the indexes of the child eelements to the field currently under validation that were marked as invalid with `AddArrayElementValidationErrors`.

func (*Context) Errors

func (c *Context) Errors() []error

Errors returns this validation context's errors. The errors returned are NOT validation errors but operation errors (such as database error). Because each rule on each field has its own Context, the returned array will only contain errors related to the current field and the current rule.

func (*Context) Path

func (c *Context) Path() *walk.Path

Path returns the exact Path to the current element. The path is relative to the root element. If you are compositing rule sets in your validation, the path returned is NOT relative to the root of the current rule set.

You can use this path to inject validation errors using AddValidationError and MergeValidationErrors.

type DateComparisonValidator

type DateComparisonValidator struct {
	BaseValidator
	Date time.Time
}

DateComparisonValidator factorized date comparison validator for static dates (before, after, etc.)

func (*DateComparisonValidator) Config

func (c *DateComparisonValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*DateComparisonValidator) DB

func (c *DateComparisonValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*DateComparisonValidator) Lang

func (c *DateComparisonValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*DateComparisonValidator) Logger

func (c *DateComparisonValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*DateComparisonValidator) MessagePlaceholders

func (v *DateComparisonValidator) MessagePlaceholders(_ *Context) []string

MessagePlaceholders returns the ":date" placeholder.

type DateEqualsFieldValidator

type DateEqualsFieldValidator struct {
	DateFieldComparisonValidator
}

DateEqualsFieldValidator validates the field under validation must be a date (`time.Time`) equal to all the other dates matched by the specified path.

func DateEqualsField

func DateEqualsField(path string) *DateEqualsFieldValidator

DateEqualsField the field under validation must be a date (`time.Time`) equal to the date field identified by the given path.

func (*DateEqualsFieldValidator) Config

func (c *DateEqualsFieldValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*DateEqualsFieldValidator) DB

func (c *DateEqualsFieldValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*DateEqualsFieldValidator) Lang

func (c *DateEqualsFieldValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*DateEqualsFieldValidator) Logger

func (c *DateEqualsFieldValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*DateEqualsFieldValidator) Name

func (v *DateEqualsFieldValidator) Name() string

Name returns the string name of the validator.

func (*DateEqualsFieldValidator) Validate

func (v *DateEqualsFieldValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type DateEqualsValidator

type DateEqualsValidator struct {
	DateComparisonValidator
}

DateEqualsValidator validates the field under validation must be a date (`time.Time`) equal to the specified date.

func DateEquals

func DateEquals(date time.Time) *DateEqualsValidator

DateEquals the field under validation must be a date (`time.Time`) equal to the given date.

func (*DateEqualsValidator) Config

func (c *DateEqualsValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*DateEqualsValidator) DB

func (c *DateEqualsValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*DateEqualsValidator) Lang

func (c *DateEqualsValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*DateEqualsValidator) Logger

func (c *DateEqualsValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*DateEqualsValidator) Name

func (v *DateEqualsValidator) Name() string

Name returns the string name of the validator.

func (*DateEqualsValidator) Validate

func (v *DateEqualsValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type DateFieldComparisonValidator

type DateFieldComparisonValidator struct {
	BaseValidator
	Path *walk.Path
}

DateFieldComparisonValidator factorized date comparison validator for field dates (before field, after field, etc.)

func (*DateFieldComparisonValidator) Config

func (c *DateFieldComparisonValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*DateFieldComparisonValidator) DB

func (c *DateFieldComparisonValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*DateFieldComparisonValidator) Lang

func (c *DateFieldComparisonValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*DateFieldComparisonValidator) Logger

func (c *DateFieldComparisonValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*DateFieldComparisonValidator) MessagePlaceholders

func (v *DateFieldComparisonValidator) MessagePlaceholders(_ *Context) []string

MessagePlaceholders returns the ":date" placeholder.

type DateValidator

type DateValidator struct {
	BaseValidator
	Formats []string
}

DateValidator validates the field under validation must be a string representing a date.

func Date

func Date(acceptedFormats ...string) *DateValidator

Date the field under validation must be a string representing a date. On successful validation, converts the value to `time.Time`.

The date must match at least one of the provided date formats (by order of preference). The format uses the same syntax as Go's standard datetime format. If no format is given the "2006-01-02" format is used.

func (*DateValidator) Config

func (c *DateValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*DateValidator) DB

func (c *DateValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*DateValidator) IsType

func (v *DateValidator) IsType() bool

IsType returns true.

func (*DateValidator) Lang

func (c *DateValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*DateValidator) Logger

func (c *DateValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*DateValidator) Name

func (v *DateValidator) Name() string

Name returns the string name of the validator.

func (*DateValidator) Validate

func (v *DateValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type DifferentValidator

type DifferentValidator struct {
	BaseValidator
	Path *walk.Path
}

DifferentValidator validates the field under validation is not equal to the field identified by the given path. Values of different types are never equal. Files are not checked and will never pass this validator. For arrays, objects and numbers, the values are compared using `reflect.DeepEqual()`. For numbers, make sure the two compared numbers have the same type. A `uint` with value `1` will be considered different from an `int` with value `1`.

func Different

func Different(path string) *DifferentValidator

Different validates the field under validation is not equal to the field identified by the given path. Values of different types are never equal. Files are not checked and will never pass this validator. For arrays, objects and numbers, the values are compared using `reflect.DeepEqual()`. For numbers, make sure the two compared numbers have the same type. A `uint` with value `1` will be considered different from an `int` with value `1`.

func (*DifferentValidator) Config

func (c *DifferentValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*DifferentValidator) DB

func (c *DifferentValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*DifferentValidator) Lang

func (c *DifferentValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*DifferentValidator) Logger

func (c *DifferentValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*DifferentValidator) MessagePlaceholders

func (v *DifferentValidator) MessagePlaceholders(_ *Context) []string

MessagePlaceholders returns the ":other" placeholder.

func (*DifferentValidator) Name

func (v *DifferentValidator) Name() string

Name returns the string name of the validator.

func (*DifferentValidator) Validate

func (v *DifferentValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type DigitsValidator

type DigitsValidator struct {
	RegexValidator
}

DigitsValidator the field under validation must be a string that only contains digits.

func Digits

func Digits() *DigitsValidator

Digits the field under validation must be a string that only contains digits.

func (*DigitsValidator) Config

func (c *DigitsValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*DigitsValidator) DB

func (c *DigitsValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*DigitsValidator) Lang

func (c *DigitsValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*DigitsValidator) Logger

func (c *DigitsValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*DigitsValidator) Name

func (v *DigitsValidator) Name() string

Name returns the string name of the validator.

type DistinctValidator

type DistinctValidator[T comparable] struct {
	BaseValidator
}

DistinctValidator validates the field under validation must be an array having distinct values.

func Distinct

func Distinct[T comparable]() *DistinctValidator[T]

Distinct the field under validation must be an array having distinct values.

func (*DistinctValidator) Config

func (c *DistinctValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*DistinctValidator) DB

func (c *DistinctValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*DistinctValidator) Lang

func (c *DistinctValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*DistinctValidator) Logger

func (c *DistinctValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*DistinctValidator[T]) Name

func (v *DistinctValidator[T]) Name() string

Name returns the string name of the validator.

func (*DistinctValidator[T]) Validate

func (v *DistinctValidator[T]) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type DoesntEndWithValidator added in v5.1.0

type DoesntEndWithValidator struct {
	BaseValidator
	Suffix []string
}

DoesntEndWithValidator the field under validation must be a string not ending with any of the specified prefixes.

func DoesntEndWith added in v5.1.0

func DoesntEndWith(suffix ...string) *DoesntEndWithValidator

DoesntEndWith the field under validation must be a string not ending with any of the specified prefixes.

func (*DoesntEndWithValidator) Config added in v5.1.0

func (c *DoesntEndWithValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*DoesntEndWithValidator) DB added in v5.1.0

func (c *DoesntEndWithValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*DoesntEndWithValidator) Lang added in v5.1.0

func (c *DoesntEndWithValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*DoesntEndWithValidator) Logger added in v5.1.0

func (c *DoesntEndWithValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*DoesntEndWithValidator) MessagePlaceholders added in v5.1.0

func (v *DoesntEndWithValidator) MessagePlaceholders(_ *Context) []string

MessagePlaceholders returns the ":values" placeholder.

func (*DoesntEndWithValidator) Name added in v5.1.0

func (v *DoesntEndWithValidator) Name() string

Name returns the string name of the validator.

func (*DoesntEndWithValidator) Validate added in v5.1.0

func (v *DoesntEndWithValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type DoesntStartWithValidator added in v5.1.0

type DoesntStartWithValidator struct {
	BaseValidator
	Prefix []string
}

DoesntStartWithValidator the field under validation must be a string not starting with any of the specified prefixes.

func DoesntStartWith added in v5.1.0

func DoesntStartWith(prefix ...string) *DoesntStartWithValidator

DoesntStartWith the field under validation must be a string not starting with any of the specified prefixes.

func (*DoesntStartWithValidator) Config added in v5.1.0

func (c *DoesntStartWithValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*DoesntStartWithValidator) DB added in v5.1.0

func (c *DoesntStartWithValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*DoesntStartWithValidator) Lang added in v5.1.0

func (c *DoesntStartWithValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*DoesntStartWithValidator) Logger added in v5.1.0

func (c *DoesntStartWithValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*DoesntStartWithValidator) MessagePlaceholders added in v5.1.0

func (v *DoesntStartWithValidator) MessagePlaceholders(_ *Context) []string

MessagePlaceholders returns the ":values" placeholder.

func (*DoesntStartWithValidator) Name added in v5.1.0

func (v *DoesntStartWithValidator) Name() string

Name returns the string name of the validator.

func (*DoesntStartWithValidator) Validate added in v5.1.0

func (v *DoesntStartWithValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type EmailValidator

type EmailValidator struct {
	BaseValidator
}

EmailValidator the field under validation must be a string that can be parsed using Go's standard `mail.ParseAddress` function.

The email address format is defined by RFC 5322. For example:

  • Barry Gibbs <bg@example.com>
  • foo@example.com

This validator is not enough in itself to properly validate an email address. The only way to ensure an email address is valid is by sending a confirmation email.

On successful validation, converts the value to `string`.

func Email

func Email() *EmailValidator

Email the field under validation must be a string that can be parsed using Go's standard `mail.ParseAddress` function.

The email address format is defined by RFC 5322. For example:

  • Barry Gibbs <bg@example.com>
  • foo@example.com

This validator is not enough in itself to properly validate an email address. The only way to ensure an email address is valid is by sending a confirmation email.

On successful validation, converts the value to `string`.

func (*EmailValidator) Config

func (c *EmailValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*EmailValidator) DB

func (c *EmailValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*EmailValidator) IsType

func (v *EmailValidator) IsType() bool

IsType returns true.

func (*EmailValidator) Lang

func (c *EmailValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*EmailValidator) Logger

func (c *EmailValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*EmailValidator) Name

func (v *EmailValidator) Name() string

Name returns the string name of the validator.

func (*EmailValidator) Validate

func (v *EmailValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type EndsWithValidator

type EndsWithValidator struct {
	BaseValidator
	Suffix []string
}

EndsWithValidator the field under validation must be a string ending with at least one of the specified suffixes.

func EndsWith

func EndsWith(suffix ...string) *EndsWithValidator

EndsWith the field under validation must be a string ending with at least one of the specified prefixes.

func (*EndsWithValidator) Config

func (c *EndsWithValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*EndsWithValidator) DB

func (c *EndsWithValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*EndsWithValidator) Lang

func (c *EndsWithValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*EndsWithValidator) Logger

func (c *EndsWithValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*EndsWithValidator) MessagePlaceholders

func (v *EndsWithValidator) MessagePlaceholders(_ *Context) []string

MessagePlaceholders returns the ":values" placeholder.

func (*EndsWithValidator) Name

func (v *EndsWithValidator) Name() string

Name returns the string name of the validator.

func (*EndsWithValidator) Validate

func (v *EndsWithValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type ErrorResponse

type ErrorResponse struct {
	Body  *Errors `json:"body,omitempty"`
	Query *Errors `json:"query,omitempty"`
}

ErrorResponse HTTP response format for validation errors.

type Errors

type Errors struct {
	Fields   FieldsErrors `json:"fields,omitempty"`
	Elements ArrayErrors  `json:"elements,omitempty"`
	Errors   []string     `json:"errors,omitempty"`
}

Errors structure representing the errors associated with an element. If the element is an object (`map[string]any`), `Fields` represents the errors associated with this object's fields. The key is the name of the field. `Fields` may be `nil`. If the element is a slice, `Elements` represents the errors associated with each element of the array. See `ArrayErrors` for more details.

func Validate

func Validate(options *Options) (*Errors, []error)

Validate the given data using the given `Options`. If all validation rules pass and no error occurred, the first returned value will be `nil`.

The second returned value is a slice of error that occurred during validation. These errors are not validation errors but error raised when a validator could not be executed correctly. For example if a validator using the database generated a DB error.

The `Options.Data` may be modified thanks to type rules.

func (*Errors) Add

func (e *Errors) Add(path *walk.Path, message string)

Add an error message to the element identified by the given path. If a step in the path of type `PathTypeArray` doesn't provide an index, -1 will be used to indicate that the element doesn't exist. Creates all missing elements in the path.

Note that the walking behavior is slightly different from `walk.Path.Walk`: if the first step in the path is of type `walk.PathTypeObject`, it will be considered as the root element and skipped. This allows this implementation to know the root element is an object and create the `FieldsErrors` accordingly.

func (*Errors) Merge

func (e *Errors) Merge(path *walk.Path, errors *Errors)

Merge the given errors into this bag of errors at the given path. This can be used when a validator uses nested validation and wants to add the results in the higher-level validation errors.

Missing path segments will be added automatically. Elements from the given errors are NOT cloned. Therefore there can be side-effects if you modify them after the call of `Merge`.

type ExistsArrayValidator

type ExistsArrayValidator[T any] struct {
	BaseValidator
	Transform func(val T) clause.Expr
	Table     string
	Column    string
}

ExistsArrayValidator validates the field under validation must be an array and all of its elements must exist. The type `T` is the type of the elements of the array under validation.

This is preferable to use this validation rule on the array instead of `Exists` on each array element because this rule will only execute a single SQL query instead of as many as there are elements in the array.

If provided, the `Transform` function is called on every array element to transform them into a raw expression. For example to transform a number into `(123::int)` for Postgres to prevent some type errors.

func ExistsArray

func ExistsArray[T any](table, column string, transform func(val T) clause.Expr) *ExistsArrayValidator[T]

ExistsArray validates the field under validation must be an array and all of its elements must exist. The type `T` is the type of the elements of the array under validation.

This is preferable to use this validation rule on the array instead of `Exists` on each array element because this rule will only execute a single SQL query instead of as many as there are elements in the array.

If provided, the `Transform` function is called on every array element to transform them into a raw expression. For example to transform a number into `(123::int)` for Postgres to prevent some type errors.

func (*ExistsArrayValidator) Config

func (c *ExistsArrayValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*ExistsArrayValidator) DB

func (c *ExistsArrayValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*ExistsArrayValidator) Lang

func (c *ExistsArrayValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*ExistsArrayValidator) Logger

func (c *ExistsArrayValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*ExistsArrayValidator[T]) Name

func (v *ExistsArrayValidator[T]) Name() string

Name returns the string name of the validator.

func (*ExistsArrayValidator[T]) Validate

func (v *ExistsArrayValidator[T]) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type ExistsValidator

type ExistsValidator struct {
	UniqueValidator
}

ExistsValidator validates the field under validation must exist in database according to the provided database scope. Existence is checked using a COUNT query.

func Exists

func Exists(scope func(db *gorm.DB, val any) *gorm.DB) *ExistsValidator

Exists validates the field under validation must have exist database according to the provided database scope. Existence is checked using a COUNT query.

 v.Exists(func(db *gorm.DB, val any) *gorm.DB {
	return db.Model(&model.User{}).Where(clause.PrimaryKey, val)
 })

func (*ExistsValidator) Config

func (c *ExistsValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*ExistsValidator) DB

func (c *ExistsValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*ExistsValidator) Lang

func (c *ExistsValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*ExistsValidator) Logger

func (c *ExistsValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*ExistsValidator) Name

func (v *ExistsValidator) Name() string

Name returns the string name of the validator.

func (*ExistsValidator) Validate

func (v *ExistsValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type ExtensionValidator

type ExtensionValidator struct {
	BaseValidator
	Extensions []string
}

ExtensionValidator validates the field under validation must be a file whose filename has one of the specified extensions as suffix. Multi-files are supported (all files must satisfy the criteria).

func Extension

func Extension(extensions ...string) *ExtensionValidator

Extension the field under validation must be a file whose filename has one of the specified extensions as suffix. Don't include the dot in the extension. Composite extensions (e.g. "tar.gz") are supported.

Multi-files are supported (all files must satisfy the criteria).

func (*ExtensionValidator) Config

func (c *ExtensionValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*ExtensionValidator) DB

func (c *ExtensionValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*ExtensionValidator) Lang

func (c *ExtensionValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*ExtensionValidator) Logger

func (c *ExtensionValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*ExtensionValidator) MessagePlaceholders

func (v *ExtensionValidator) MessagePlaceholders(_ *Context) []string

MessagePlaceholders returns the ":values" placeholder.

func (*ExtensionValidator) Name

func (v *ExtensionValidator) Name() string

Name returns the string name of the validator.

func (*ExtensionValidator) Validate

func (v *ExtensionValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type ExtraRequest

type ExtraRequest struct{}

ExtraRequest extra key used when validating a request so the request's information is accessible to validation rules

type Field

type Field struct {
	Path       *walk.Path
	Elements   *Field
	Validators []Validator
	// contains filtered or unexported fields
}

Field representation of a single field in the data being validated. Provides useful information based on its validators (if required, nullable, etc).

func (*Field) IsArray

func (f *Field) IsArray() bool

IsArray check if a field has the "array" rule

func (*Field) IsNullable

func (f *Field) IsNullable() bool

IsNullable check if a field has the "nullable" rule

func (*Field) IsObject

func (f *Field) IsObject() bool

IsObject check if a field has the "object" rule

func (*Field) IsRequired

func (f *Field) IsRequired(ctx *Context) bool

IsRequired check if a field has the "required" rule

func (*Field) PrefixDepth

func (f *Field) PrefixDepth() uint

PrefixDepth When using composition, `prefixDepth` allows to truncate the path to the validated element in order to retrieve the root object or array relative to the composed RuleSet.

type FieldRules

type FieldRules struct {
	// TODO what behavior if there are duplicates? If it ever becomes a problem, can probably merge the Lists. But it's unnecessary for now.
	Rules FieldRulesConverter
	Path  string
}

FieldRules structure associating a path (see `walk.Path`) identifying a field with a `FieldRulesApplier` (a `List` of rules or another `RuleSet` via composition).

type FieldRulesConverter

type FieldRulesConverter interface {
	// contains filtered or unexported methods
}

FieldRulesConverter types implementing this interface define their behavior when converting a `FieldRules` to `Rules`. This enables rule sets composition.

type FieldsErrors

type FieldsErrors map[string]*Errors

FieldsErrors representing the errors associated with the fields of an object, the key being the name of the field.

func (FieldsErrors) Add

func (e FieldsErrors) Add(path *walk.Path, message string)

Add an error message to the element identified by the given path. Creates all missing elements in the path.

func (FieldsErrors) Merge

func (e FieldsErrors) Merge(path *walk.Path, errors *Errors)

Merge the given errors into this bag of errors at the given path.

type FileCountBetweenValidator

type FileCountBetweenValidator struct {
	BaseValidator
	Min uint
	Max uint
}

FileCountBetweenValidator validates the field under validation must be a multi-files with a number of files between the specified min and max.

func FileCountBetween

func FileCountBetween(min, max uint) *FileCountBetweenValidator

FileCountBetween the field under validation must be a multi-files with a number of files between the specified min and max.

func (*FileCountBetweenValidator) Config

func (c *FileCountBetweenValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*FileCountBetweenValidator) DB

func (c *FileCountBetweenValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*FileCountBetweenValidator) Lang

func (c *FileCountBetweenValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*FileCountBetweenValidator) Logger

func (c *FileCountBetweenValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*FileCountBetweenValidator) MessagePlaceholders

func (v *FileCountBetweenValidator) MessagePlaceholders(_ *Context) []string

MessagePlaceholders returns the ":min" and ":max" placeholders.

func (*FileCountBetweenValidator) Name

Name returns the string name of the validator.

func (*FileCountBetweenValidator) Validate

func (v *FileCountBetweenValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type FileCountValidator

type FileCountValidator struct {
	BaseValidator
	Count uint
}

FileCountValidator validates the field under validation must be a multi-files with exactly the specified number of files.

func FileCount

func FileCount(count uint) *FileCountValidator

FileCount the field under validation must be a multi-files with exactly the specified number of files.

func (*FileCountValidator) Config

func (c *FileCountValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*FileCountValidator) DB

func (c *FileCountValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*FileCountValidator) Lang

func (c *FileCountValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*FileCountValidator) Logger

func (c *FileCountValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*FileCountValidator) MessagePlaceholders

func (v *FileCountValidator) MessagePlaceholders(_ *Context) []string

MessagePlaceholders returns the ":value" placeholder.

func (*FileCountValidator) Name

func (v *FileCountValidator) Name() string

Name returns the string name of the validator.

func (*FileCountValidator) Validate

func (v *FileCountValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type FileValidator

type FileValidator struct {
	BaseValidator
}

FileValidator validates the field under validation must be a file. Multi-files are supported.

func File

func File() *FileValidator

File the field under validation must be a file. Multi-files are supported.

func (*FileValidator) Config

func (c *FileValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*FileValidator) DB

func (c *FileValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*FileValidator) IsType

func (v *FileValidator) IsType() bool

IsType returns true.

func (*FileValidator) Lang

func (c *FileValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*FileValidator) Logger

func (c *FileValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*FileValidator) Name

func (v *FileValidator) Name() string

Name returns the string name of the validator.

func (*FileValidator) Validate

func (v *FileValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type Float32Validator

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

Float32Validator validator for the "float32" rule.

func Float32

func Float32() *Float32Validator

Float32 the field under validation must be a number and fit into Go's `float32` type. If the source number is an integer, the validator makes sure `float32` is capable of representing it without loss or rounding.

Strings that can be converted to the target type are accepted. This rule converts the field to `float32` if it passes.

func (*Float32Validator) IsType

func (v *Float32Validator) IsType() bool

func (*Float32Validator) Name

func (v *Float32Validator) Name() string

func (*Float32Validator) Validate

func (v *Float32Validator) Validate(ctx *Context) bool

type Float64Validator

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

Float64Validator validator for the "float64" rule.

func Float64

func Float64() *Float64Validator

Float64 the field under validation must be a number and fit into Go's `float64` type. If the source number is an integer, the validator makes sure `float64` is capable of representing it without loss or rounding.

Strings that can be converted to the target type are accepted. This rule converts the field to `float64` if it passes.

func (*Float64Validator) IsType

func (v *Float64Validator) IsType() bool

func (*Float64Validator) Name

func (v *Float64Validator) Name() string

func (*Float64Validator) Validate

func (v *Float64Validator) Validate(ctx *Context) bool

type GreaterThanEqualValidator

type GreaterThanEqualValidator struct {
	ComparisonValidator
}

GreaterThanEqualValidator validates the field under validation is greater than the field identified by the given path. See `ComparisonValidator` for more details.

func GreaterThanEqual

func GreaterThanEqual(path string) *GreaterThanEqualValidator

GreaterThanEqual validates the field under validation is greater or equal to the field identified by the given path. Mixed types are supported, meaning you can use this rule for the following (non-exhaustive) cases:

  • Compare the length of two strings
  • Compare the value of two numeric fields
  • Compare a numeric field with the length of a string or a string length with a numeric field
  • Compare a numeric field with the number of elements in an array
  • Compare the number of keys in an object with a numeric field
  • Compare a file (or multifile) size with a numeric field. The number of KiB of each file is rounded up (ceil).

func (*GreaterThanEqualValidator) Config

func (c *GreaterThanEqualValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*GreaterThanEqualValidator) DB

func (c *GreaterThanEqualValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*GreaterThanEqualValidator) Lang

func (c *GreaterThanEqualValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*GreaterThanEqualValidator) Logger

func (c *GreaterThanEqualValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*GreaterThanEqualValidator) Name

Name returns the string name of the validator.

func (*GreaterThanEqualValidator) Validate

func (v *GreaterThanEqualValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type GreaterThanValidator

type GreaterThanValidator struct {
	ComparisonValidator
}

GreaterThanValidator validates the field under validation is greater than the field identified by the given path. See `ComparisonValidator` for more details.

func GreaterThan

func GreaterThan(path string) *GreaterThanValidator

GreaterThan validates the field under validation is greater than the field identified by the given path. Mixed types are supported, meaning you can use this rule for the following (non-exhaustive) cases:

  • Compare the length of two strings
  • Compare the value of two numeric fields
  • Compare a numeric field with the length of a string or a string length with a numeric field
  • Compare a numeric field with the number of elements in an array
  • Compare the number of keys in an object with a numeric field
  • Compare a file (or multifile) size with a numeric field. The number of KiB of each file is rounded up (ceil).

func (*GreaterThanValidator) Config

func (c *GreaterThanValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*GreaterThanValidator) DB

func (c *GreaterThanValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*GreaterThanValidator) Lang

func (c *GreaterThanValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*GreaterThanValidator) Logger

func (c *GreaterThanValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*GreaterThanValidator) Name

func (v *GreaterThanValidator) Name() string

Name returns the string name of the validator.

func (*GreaterThanValidator) Validate

func (v *GreaterThanValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type IPValidator

type IPValidator struct{ BaseValidator }

IPValidator the field under validation must be a string representing a valid IPv4 or IPv6. If validation passes, the value is converted to `net.IP`.

func IP

func IP() *IPValidator

IP the field under validation must be a string representing a valid IPv4 or IPv6. If validation passes, the value is converted to `net.IP`.

func (*IPValidator) Config

func (c *IPValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*IPValidator) DB

func (c *IPValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*IPValidator) IsType

func (v *IPValidator) IsType() bool

IsType returns true.

func (*IPValidator) Lang

func (c *IPValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*IPValidator) Logger

func (c *IPValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*IPValidator) Name

func (v *IPValidator) Name() string

Name returns the string name of the validator.

func (*IPValidator) Validate

func (v *IPValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type IPv4Validator

type IPv4Validator struct{ IPValidator }

IPv4Validator the field under validation must be a string representing a valid IPv4. If validation passes, the value is converted to `net.IP`.

func IPv4

func IPv4() *IPv4Validator

IPv4 the field under validation must be a string representing a valid IPv4. If validation passes, the value is converted to `net.IP`.

func (*IPv4Validator) Config

func (c *IPv4Validator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*IPv4Validator) DB

func (c *IPv4Validator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*IPv4Validator) Lang

func (c *IPv4Validator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*IPv4Validator) Logger

func (c *IPv4Validator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*IPv4Validator) Name

func (v *IPv4Validator) Name() string

Name returns the string name of the validator.

func (*IPv4Validator) Validate

func (v *IPv4Validator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type IPv6Validator

type IPv6Validator struct{ IPValidator }

IPv6Validator the field under validation must be a string representing a valid IPv6. If validation passes, the value is converted to `net.IP`.

func IPv6

func IPv6() *IPv6Validator

IPv6 the field under validation must be a string representing a valid IPv6. If validation passes, the value is converted to `net.IP`.

func (*IPv6Validator) Config

func (c *IPv6Validator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*IPv6Validator) DB

func (c *IPv6Validator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*IPv6Validator) Lang

func (c *IPv6Validator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*IPv6Validator) Logger

func (c *IPv6Validator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*IPv6Validator) Name

func (v *IPv6Validator) Name() string

Name returns the string name of the validator.

func (*IPv6Validator) Validate

func (v *IPv6Validator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type ImageValidator

type ImageValidator struct {
	MIMEValidator
}

ImageValidator validates the field under validation must be an image file. Multi-files are supported (all files must satisfy the criteria).

func Image

func Image() *ImageValidator

Image the field under validation must be an image file. Multi-files are supported (all files must satisfy the criteria).

Accepted MIME types are defined by `ImageMIMETypes`.

func (*ImageValidator) Config

func (c *ImageValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*ImageValidator) DB

func (c *ImageValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*ImageValidator) Lang

func (c *ImageValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*ImageValidator) Logger

func (c *ImageValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*ImageValidator) Name

func (v *ImageValidator) Name() string

Name returns the string name of the validator.

type InFieldValidator

type InFieldValidator[T comparable] struct {
	BaseValidator
	Path *walk.Path
}

InFieldValidator validates the field under validation must be in at least one of the arrays matched by the specified path.

func InField

func InField[T comparable](path string) *InFieldValidator[T]

InField the field under validation must be in at least one of the arrays matched by the specified path.

func (*InFieldValidator) Config

func (c *InFieldValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*InFieldValidator) DB

func (c *InFieldValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*InFieldValidator) Lang

func (c *InFieldValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*InFieldValidator) Logger

func (c *InFieldValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*InFieldValidator[T]) MessagePlaceholders

func (v *InFieldValidator[T]) MessagePlaceholders(_ *Context) []string

MessagePlaceholders returns the ":other" placeholder.

func (*InFieldValidator[T]) Name

func (v *InFieldValidator[T]) Name() string

Name returns the string name of the validator.

func (*InFieldValidator[T]) Validate

func (v *InFieldValidator[T]) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria. Always return false if the validated value is not of type `T` or the matched arrays are not of type `[]T`.

type InValidator

type InValidator[T comparable] struct {
	BaseValidator
	Values []T
}

InValidator validates the field under validation must be a one of the given values.

func In

func In[T comparable](values []T) *InValidator[T]

In the field under validation must be a one of the given values.

func (*InValidator) Config

func (c *InValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*InValidator) DB

func (c *InValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*InValidator) Lang

func (c *InValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*InValidator) Logger

func (c *InValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*InValidator[T]) MessagePlaceholders

func (v *InValidator[T]) MessagePlaceholders(_ *Context) []string

MessagePlaceholders returns the ":values placeholder.

func (*InValidator[T]) Name

func (v *InValidator[T]) Name() string

Name returns the string name of the validator.

func (*InValidator[T]) Validate

func (v *InValidator[T]) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria. Always return false if the validated value is not of type `T`.

type Int16Validator

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

Int16Validator validator for the "int16" rule.

func Int16

func Int16() *Int16Validator

Int16 the field under validation must be an integer and fit into Go's `int16` type. If the source number is a float, the validator makes sure the value is within the range of integers that the float can accurately represent.

Floats are only accepted if they don't have a decimal. Strings that can be converted to the target type are accepted. This rule converts the field to `int16` if it passes.

func (*Int16Validator) IsType

func (v *Int16Validator) IsType() bool

IsType returns true

func (*Int16Validator) Name

func (v *Int16Validator) Name() string

func (*Int16Validator) Validate

func (v *Int16Validator) Validate(ctx *Context) bool

type Int32Validator

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

Int32Validator validator for the "int32" rule.

func Int32

func Int32() *Int32Validator

Int32 the field under validation must be an integer and fit into Go's `int32` type. If the source number is a float, the validator makes sure the value is within the range of integers that the float can accurately represent.

Floats are only accepted if they don't have a decimal. Strings that can be converted to the target type are accepted. This rule converts the field to `int32` if it passes.

func (*Int32Validator) IsType

func (v *Int32Validator) IsType() bool

IsType returns true

func (*Int32Validator) Name

func (v *Int32Validator) Name() string

func (*Int32Validator) Validate

func (v *Int32Validator) Validate(ctx *Context) bool

type Int64Validator

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

Int64Validator validator for the "int64" rule.

func Int64

func Int64() *Int64Validator

Int64 the field under validation must be an integer and fit into Go's `int64` type. If the source number is a float, the validator makes sure the value is within the range of integers that the float can accurately represent.

Floats are only accepted if they don't have a decimal. Strings that can be converted to the target type are accepted. This rule converts the field to `int64` if it passes.

func (*Int64Validator) IsType

func (v *Int64Validator) IsType() bool

IsType returns true

func (*Int64Validator) Name

func (v *Int64Validator) Name() string

func (*Int64Validator) Validate

func (v *Int64Validator) Validate(ctx *Context) bool

type Int8Validator

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

Int8Validator validator for the "int8" rule.

func Int8

func Int8() *Int8Validator

Int8 the field under validation must be an integer and fit into Go's `int8` type. If the source number is a float, the validator makes sure the value is within the range of integers that the float can accurately represent.

Floats are only accepted if they don't have a decimal. Strings that can be converted to the target type are accepted. This rule converts the field to `int8` if it passes.

func (*Int8Validator) IsType

func (v *Int8Validator) IsType() bool

IsType returns true

func (*Int8Validator) Name

func (v *Int8Validator) Name() string

func (*Int8Validator) Validate

func (v *Int8Validator) Validate(ctx *Context) bool

type IntValidator

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

IntValidator validator for the "int" rule.

func Int

func Int() *IntValidator

Int the field under validation must be an integer and fit into Go's `int` type. If the source number is a float, the validator makes sure the value is within the range of integers that the float can accurately represent.

Floats are only accepted if they don't have a decimal. Strings that can be converted to the target type are accepted. This rule converts the field to `int` if it passes.

func (*IntValidator) IsType

func (v *IntValidator) IsType() bool

IsType returns true

func (*IntValidator) Name

func (v *IntValidator) Name() string

func (*IntValidator) Validate

func (v *IntValidator) Validate(ctx *Context) bool

type JSONValidator

type JSONValidator struct{ BaseValidator }

JSONValidator validates the field under validation must be a valid JSON string.

func JSON

func JSON() *JSONValidator

JSON the field under validation must be a valid JSON string. Unmarshals the string and sets the field value to the unmarshalled result.

func (*JSONValidator) Config

func (c *JSONValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*JSONValidator) DB

func (c *JSONValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*JSONValidator) IsType

func (v *JSONValidator) IsType() bool

IsType returns true.

func (*JSONValidator) Lang

func (c *JSONValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*JSONValidator) Logger

func (c *JSONValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*JSONValidator) Name

func (v *JSONValidator) Name() string

Name returns the string name of the validator.

func (*JSONValidator) Validate

func (v *JSONValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type KeysInValidator added in v5.1.0

type KeysInValidator struct {
	BaseValidator
	Keys []string
}

KeysInValidator the field under validation must be an object and all its keys must be equal to one of the given values.

func KeysIn added in v5.1.0

func KeysIn(keys ...string) *KeysInValidator

KeysIn the field under validation must be an object and all its keys must be equal to one of the given values.

func (*KeysInValidator) Config added in v5.1.0

func (c *KeysInValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*KeysInValidator) DB added in v5.1.0

func (c *KeysInValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*KeysInValidator) Lang added in v5.1.0

func (c *KeysInValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*KeysInValidator) Logger added in v5.1.0

func (c *KeysInValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*KeysInValidator) MessagePlaceholders added in v5.1.0

func (v *KeysInValidator) MessagePlaceholders(_ *Context) []string

MessagePlaceholders returns the ":values" placeholder.

func (*KeysInValidator) Name added in v5.1.0

func (v *KeysInValidator) Name() string

Name returns the string name of the validator.

func (*KeysInValidator) Validate added in v5.1.0

func (v *KeysInValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type List

type List []Validator

List of validators which will be applied on the field. The validators are executed in the order of the slice.

type LowerThanEqualValidator

type LowerThanEqualValidator struct {
	ComparisonValidator
}

LowerThanEqualValidator validates the field under validation is lower or equal to the field identified by the given path. See `ComparisonValidator` for more details.

func LowerThanEqual

func LowerThanEqual(path string) *LowerThanEqualValidator

LowerThanEqual validates the field under validation is lower or equal to the field identified by the given path. Mixed types are supported, meaning you can use this rule for the following (non-exhaustive) cases:

  • Compare the length of two strings
  • Compare the value of two numeric fields
  • Compare a numeric field with the length of a string or a string length with a numeric field
  • Compare a numeric field with the number of elements in an array
  • Compare the number of keys in an object with a numeric field
  • Compare a file (or multifile) size with a numeric field. The number of KiB of each file is rounded up (ceil).

func (*LowerThanEqualValidator) Config

func (c *LowerThanEqualValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*LowerThanEqualValidator) DB

func (c *LowerThanEqualValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*LowerThanEqualValidator) Lang

func (c *LowerThanEqualValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*LowerThanEqualValidator) Logger

func (c *LowerThanEqualValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*LowerThanEqualValidator) Name

func (v *LowerThanEqualValidator) Name() string

Name returns the string name of the validator.

func (*LowerThanEqualValidator) Validate

func (v *LowerThanEqualValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type LowerThanValidator

type LowerThanValidator struct {
	ComparisonValidator
}

LowerThanValidator validates the field under validation is lower than the field identified by the given path. See `ComparisonValidator` for more details.

func LowerThan

func LowerThan(path string) *LowerThanValidator

LowerThan validates the field under validation is lower than the field identified by the given path. Mixed types are supported, meaning you can use this rule for the following (non-exhaustive) cases:

  • Compare the length of two strings
  • Compare the value of two numeric fields
  • Compare a numeric field with the length of a string or a string length with a numeric field
  • Compare a numeric field with the number of elements in an array
  • Compare the number of keys in an object with a numeric field
  • Compare a file (or multifile) size with a numeric field. The number of KiB of each file is rounded up (ceil).

func (*LowerThanValidator) Config

func (c *LowerThanValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*LowerThanValidator) DB

func (c *LowerThanValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*LowerThanValidator) Lang

func (c *LowerThanValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*LowerThanValidator) Logger

func (c *LowerThanValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*LowerThanValidator) Name

func (v *LowerThanValidator) Name() string

Name returns the string name of the validator.

func (*LowerThanValidator) Validate

func (v *LowerThanValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type MIMEValidator

type MIMEValidator struct {
	BaseValidator
	MIMETypes []string
}

MIMEValidator validates the field under validation must be a file and match one of the given MIME types. Multi-files are supported (all files must satisfy the criteria).

func MIME

func MIME(mimeTypes ...string) *MIMEValidator

MIME the field under validation must be a file and match one of the given MIME types. Multi-files are supported (all files must satisfy the criteria).

func (*MIMEValidator) Config

func (c *MIMEValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*MIMEValidator) DB

func (c *MIMEValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*MIMEValidator) Lang

func (c *MIMEValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*MIMEValidator) Logger

func (c *MIMEValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*MIMEValidator) MessagePlaceholders

func (v *MIMEValidator) MessagePlaceholders(_ *Context) []string

MessagePlaceholders returns the ":values" placeholder.

func (*MIMEValidator) Name

func (v *MIMEValidator) Name() string

Name returns the string name of the validator.

func (*MIMEValidator) Validate

func (v *MIMEValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type MaxFileCountValidator

type MaxFileCountValidator struct {
	BaseValidator
	Max uint
}

MaxFileCountValidator validates the field under validation must be a multi-files with at most the specified number of files.

func MaxFileCount

func MaxFileCount(max uint) *MaxFileCountValidator

MaxFileCount the field under validation must be a multi-files with at most the specified number of files.

func (*MaxFileCountValidator) Config

func (c *MaxFileCountValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*MaxFileCountValidator) DB

func (c *MaxFileCountValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*MaxFileCountValidator) Lang

func (c *MaxFileCountValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*MaxFileCountValidator) Logger

func (c *MaxFileCountValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*MaxFileCountValidator) MessagePlaceholders

func (v *MaxFileCountValidator) MessagePlaceholders(_ *Context) []string

MessagePlaceholders returns the ":max" placeholder.

func (*MaxFileCountValidator) Name

func (v *MaxFileCountValidator) Name() string

Name returns the string name of the validator.

func (*MaxFileCountValidator) Validate

func (v *MaxFileCountValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type MaxValidator

type MaxValidator struct {
	BaseValidator
	Max float64
}

MaxValidator validates the field under validation depending on its type.

  • Numbers are directly compared if they fit in `float64`. If they don't the rule doesn't pass.
  • Strings must have a length of at most n characters (calculated based on the number of grapheme clusters)
  • Arrays must have at most n elements
  • Objects must have at most n keys
  • Files must weight at most n KiB (for multi-files, all files must match this criteria). The number of KiB of each file is rounded up (ceil).

func Max

func Max(max float64) *MaxValidator

Max validates the field under validation depending on its type.

  • Numbers are directly compared if they fit in `float64`. If they don't the rule doesn't pass.
  • Strings must have a length of at most n characters (calculated based on the number of grapheme clusters)
  • Arrays must have at most n elements
  • Objects must have at most n keys
  • Files must weight at most n KiB (for multi-files, all files must match this criteria). The number of KiB of each file is rounded up (ceil).

func (*MaxValidator) Config

func (c *MaxValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*MaxValidator) DB

func (c *MaxValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*MaxValidator) IsTypeDependent

func (v *MaxValidator) IsTypeDependent() bool

IsTypeDependent returns true

func (*MaxValidator) Lang

func (c *MaxValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*MaxValidator) Logger

func (c *MaxValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*MaxValidator) MessagePlaceholders

func (v *MaxValidator) MessagePlaceholders(_ *Context) []string

MessagePlaceholders returns the ":max" placeholder.

func (*MaxValidator) Name

func (v *MaxValidator) Name() string

Name returns the string name of the validator.

func (*MaxValidator) Validate

func (v *MaxValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type MinFileCountValidator

type MinFileCountValidator struct {
	BaseValidator
	Min uint
}

MinFileCountValidator validates the field under validation must be a multi-files with at least the specified number of files.

func MinFileCount

func MinFileCount(min uint) *MinFileCountValidator

MinFileCount the field under validation must be a multi-files with at least the specified number of files.

func (*MinFileCountValidator) Config

func (c *MinFileCountValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*MinFileCountValidator) DB

func (c *MinFileCountValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*MinFileCountValidator) Lang

func (c *MinFileCountValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*MinFileCountValidator) Logger

func (c *MinFileCountValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*MinFileCountValidator) MessagePlaceholders

func (v *MinFileCountValidator) MessagePlaceholders(_ *Context) []string

MessagePlaceholders returns the ":min" placeholder.

func (*MinFileCountValidator) Name

func (v *MinFileCountValidator) Name() string

Name returns the string name of the validator.

func (*MinFileCountValidator) Validate

func (v *MinFileCountValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type MinValidator

type MinValidator struct {
	BaseValidator
	Min float64
}

MinValidator validates the field under validation depending on its type.

  • Numbers are directly compared if they fit in `float64`. If they don't the rule doesn't pass.
  • Strings must have a length of at least n characters (calculated based on the number of grapheme clusters)
  • Arrays must have at least n elements
  • Objects must have at least n keys
  • Files must weight at least n KiB (for multi-files, all files must match this criteria). The number of KiB of each file is rounded up (ceil).

func Min

func Min(min float64) *MinValidator

Min validates the field under validation depending on its type.

  • Numbers are directly compared if they fit in `float64`. If they don't the rule doesn't pass.
  • Strings must have a length of at least n characters (calculated based on the number of grapheme clusters)
  • Arrays must have at least n elements
  • Objects must have at least n keys
  • Files must weight at least n KiB (for multi-files, all files must match this criteria). The number of KiB of each file is rounded up (ceil).

func (*MinValidator) Config

func (c *MinValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*MinValidator) DB

func (c *MinValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*MinValidator) IsTypeDependent

func (v *MinValidator) IsTypeDependent() bool

IsTypeDependent returns true

func (*MinValidator) Lang

func (c *MinValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*MinValidator) Logger

func (c *MinValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*MinValidator) MessagePlaceholders

func (v *MinValidator) MessagePlaceholders(_ *Context) []string

MessagePlaceholders returns the ":min" placeholder.

func (*MinValidator) Name

func (v *MinValidator) Name() string

Name returns the string name of the validator.

func (*MinValidator) Validate

func (v *MinValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type NotInFieldValidator

type NotInFieldValidator[T comparable] struct {
	InFieldValidator[T]
}

NotInFieldValidator validates the field under validation must not be in any of the arrays matched by the specified path.

func NotInField

func NotInField[T comparable](path string) *NotInFieldValidator[T]

NotInField the field under validation must not be in any of the arrays matched by the specified path.

func (*NotInFieldValidator) Config

func (c *NotInFieldValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*NotInFieldValidator) DB

func (c *NotInFieldValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*NotInFieldValidator) Lang

func (c *NotInFieldValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*NotInFieldValidator) Logger

func (c *NotInFieldValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*NotInFieldValidator[T]) Name

func (v *NotInFieldValidator[T]) Name() string

Name returns the string name of the validator.

func (*NotInFieldValidator[T]) Validate

func (v *NotInFieldValidator[T]) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria. Always return false if the validated value is not of type `T`.

type NotInValidator

type NotInValidator[T comparable] struct {
	BaseValidator
	Values []T
}

NotInValidator validates the field undervalidation must not be a one of the given values.

func NotIn

func NotIn[T comparable](values []T) *NotInValidator[T]

NotIn the field under validation must not be a one of the given values.

func (*NotInValidator) Config

func (c *NotInValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*NotInValidator) DB

func (c *NotInValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*NotInValidator) Lang

func (c *NotInValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*NotInValidator) Logger

func (c *NotInValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*NotInValidator[T]) MessagePlaceholders

func (v *NotInValidator[T]) MessagePlaceholders(_ *Context) []string

MessagePlaceholders returns the ":values placeholder.

func (*NotInValidator[T]) Name

func (v *NotInValidator[T]) Name() string

Name returns the string name of the validator.

func (*NotInValidator[T]) Validate

func (v *NotInValidator[T]) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria. Always return false if the validated value is not of type `T`or the matched arrays are not of type `[]T`.

type NullableValidator

type NullableValidator struct{ BaseValidator }

NullableValidator is a special validator indicating the `nil` values are accepted. If this field under validation is not nullable (is not validated by a `NullableValidator`) and its value is `nil`, it will be removed from the input data.

func Nullable

func Nullable() *NullableValidator

Nullable indicates `nil` values are accepted. If this field under validation is not nullable and its value is `nil`, it will be removed from the input data.

func (*NullableValidator) Config

func (c *NullableValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*NullableValidator) DB

func (c *NullableValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*NullableValidator) Lang

func (c *NullableValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*NullableValidator) Logger

func (c *NullableValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*NullableValidator) Name

func (v *NullableValidator) Name() string

Name returns the string name of the validator.

func (*NullableValidator) Validate

func (v *NullableValidator) Validate(_ *Context) bool

Validate returns true.

type ObjectValidator

type ObjectValidator struct{ BaseValidator }

ObjectValidator the field under validation must be an object (`map[string]any`). If the value of the field under validation is a valid JSON string that can be unmarshalled into a `map[string]any`, converts the value to `map[string]any`.

func Object

func Object() *ObjectValidator

Object the field under validation must be an object (`map[string]any`). If the value of the field under validation is a valid JSON string that can be unmarshalled into a `map[string]any`, converts the value to `map[string]any`.

func (*ObjectValidator) Config

func (c *ObjectValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*ObjectValidator) DB

func (c *ObjectValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*ObjectValidator) IsType

func (v *ObjectValidator) IsType() bool

IsType returns true.

func (*ObjectValidator) Lang

func (c *ObjectValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*ObjectValidator) Logger

func (c *ObjectValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*ObjectValidator) Name

func (v *ObjectValidator) Name() string

Name returns the string name of the validator.

func (*ObjectValidator) Validate

func (v *ObjectValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type Options

type Options struct {
	// Context defaults to `context.Background()` if not provided.
	Context context.Context
	Data    any
	Rules   Ruler

	Now time.Time

	// Extra can be used to store any extra information. It is passed to each `Validator`
	// via the validation `Context`.
	//
	// The keys must be comparable and should not be of type
	// string or any other built-in type to avoid collisions.
	// To avoid allocating when assigning to an `interface{}`, context keys often have
	// concrete type `struct{}`. Alternatively, exported context key variables' static
	// type should be a pointer or interface.
	Extra map[any]any

	// Language used for translating validation error messages.
	// Defaults to `lang.Default`.
	Language *lang.Language
	DB       *gorm.DB
	Config   *config.Config
	Logger   *slog.Logger

	// ConvertSingleValueArrays set to true to convert fields that are expected
	// to be an array into an array with a single value.
	//
	// It is recommended to set this option to `true` when validating url-encoded requests.
	// For example, if set to `false`:
	//  field=A         --> map[string]any{"field": "A"}
	//  field=A&field=B --> map[string]any{"field": []string{"A", "B"}}
	// If set to `true` and `field` has the `Array` rule:
	//  field=A         --> map[string]any{"field": []string{"A"}}
	//  field=A&field=B --> map[string]any{"field": []string{"A", "B"}}
	ConvertSingleValueArrays bool
}

Options all the parameters required by `Validate()`.

Only `Data`, `Rules` and `Language` are mandatory. However, it is recommended to provide values for all the options in case a `Validator` requires them to function.

type RegexValidator

type RegexValidator struct {
	BaseValidator
	Regexp *regexp.Regexp
}

RegexValidator the field under validation must be a string matching the specified `*regexp.Regexp`.

func Regex

func Regex(regex *regexp.Regexp) *RegexValidator

Regex the field under validation must be a string matching the specified `*regexp.Regexp`.

func (*RegexValidator) Config

func (c *RegexValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*RegexValidator) DB

func (c *RegexValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*RegexValidator) Lang

func (c *RegexValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*RegexValidator) Logger

func (c *RegexValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*RegexValidator) MessagePlaceholders

func (v *RegexValidator) MessagePlaceholders(_ *Context) []string

MessagePlaceholders returns the ":regexp" placeholder.

func (*RegexValidator) Name

func (v *RegexValidator) Name() string

Name returns the string name of the validator.

func (*RegexValidator) Validate

func (v *RegexValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type RequiredIfValidator

type RequiredIfValidator struct {
	RequiredValidator
	Condition func(*Context) bool
}

RequiredIfValidator is the same as `RequiredValidator` but only applies the behavior described if the specified `Condition` function returns true.

func RequiredIf

func RequiredIf(condition func(*Context) bool) *RequiredIfValidator

RequiredIf is the same as `Required` but only applies the behavior described if the specified condition function returns true.

func (*RequiredIfValidator) Config

func (c *RequiredIfValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*RequiredIfValidator) DB

func (c *RequiredIfValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*RequiredIfValidator) Lang

func (c *RequiredIfValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*RequiredIfValidator) Logger

func (c *RequiredIfValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*RequiredIfValidator) Validate

func (v *RequiredIfValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type RequiredValidator

type RequiredValidator struct{ BaseValidator }

RequiredValidator the field under validation is required. If a field is absent from the input data, subsequent validators will not be executed.

If a field is `nil` and has the `Nullable` validator, this validator passes. As non-nullable fields are removed if they have a `nil` value, this validator doesn't pass if a field is `nil` and doesn't have the `Nullable` validator.

func Required

func Required() *RequiredValidator

Required the field under validation is required. If a field is absent from the input data, subsequent validators will not be executed.

If a field is `nil` and has the `Nullable` validator, this validator passes. As non-nullable fields are removed if they have a `nil` value, this validator doesn't pass if a field is `nil` and doesn't have the `Nullable` validator.

func (*RequiredValidator) Config

func (c *RequiredValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*RequiredValidator) DB

func (c *RequiredValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*RequiredValidator) Lang

func (c *RequiredValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*RequiredValidator) Logger

func (c *RequiredValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*RequiredValidator) Name

func (v *RequiredValidator) Name() string

Name returns the string name of the validator.

func (*RequiredValidator) Validate

func (v *RequiredValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type RuleSet

type RuleSet []*FieldRules

RuleSet definition of the validation rules applied on each field in the request. RuleSets are not meant to be re-used across multiple requests nor used concurrently.

func (RuleSet) AsRules

func (r RuleSet) AsRules() Rules

AsRules converts this RuleSet to a Rules structure.

type Ruler

type Ruler interface {
	AsRules() Rules
}

Ruler adapter interface to make allow both RuleSet and Rules to be used when calling `Validate()`.

type Rules

type Rules []*Field

Rules is the result of the transformation of RuleSet using `AsRules()`. It is a format that is more easily machine-readable than RuleSet.

func (Rules) AsRules

func (r Rules) AsRules() Rules

AsRules returns itself.

type SameValidator

type SameValidator struct {
	BaseValidator
	Path *walk.Path
}

SameValidator validates the field under validation is strictly equal to the field identified by the given path. Values of different types are never equal. Files are not checked and will never pass this validator. For arrays, objects and numbers, the values are compared using `reflect.DeepEqual()`. For numbers, make sure the two compared numbers have the same type. A `uint` with value `1` will be considered different from an `int` with value `1`.

func Same

func Same(path string) *SameValidator

Same validates the field under validation is strictly equal to the field identified by the given path. Values of different types are never equal. Files are not checked and will never pass this validator. For arrays, objects and numbers, the values are compared using `reflect.DeepEqual()`. For numbers, make sure the two compared numbers have the same type. A `uint` with value `1` will be considered different from an `int` with value `1`.

func (*SameValidator) Config

func (c *SameValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*SameValidator) DB

func (c *SameValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*SameValidator) Lang

func (c *SameValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*SameValidator) Logger

func (c *SameValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*SameValidator) MessagePlaceholders

func (v *SameValidator) MessagePlaceholders(_ *Context) []string

MessagePlaceholders returns the ":other" placeholder.

func (*SameValidator) Name

func (v *SameValidator) Name() string

Name returns the string name of the validator.

func (*SameValidator) Validate

func (v *SameValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type SizeValidator

type SizeValidator struct {
	BaseValidator
	Size int
}

SizeValidator validates the field under validation depending on its type.

  • Strings must have a length of n characters (calculated based on the number of grapheme clusters)
  • Arrays must have n elements
  • Objects must have n keys
  • Files must weight n KiB (for multi-files, all files must match this criteria). The number of KiB is rounded up (ceil).

func Size

func Size(size int) *SizeValidator

Size validates the field under validation depending on its type.

  • Strings must have a length of n characters (calculated based on the number of grapheme clusters)
  • Arrays must have n elements
  • Objects must have n keys
  • Files must weight n KiB (for multi-files, all files must match this criteria). The number of KiB is rounded up (ceil).

func (*SizeValidator) Config

func (c *SizeValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*SizeValidator) DB

func (c *SizeValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*SizeValidator) IsTypeDependent

func (v *SizeValidator) IsTypeDependent() bool

IsTypeDependent returns true

func (*SizeValidator) Lang

func (c *SizeValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*SizeValidator) Logger

func (c *SizeValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*SizeValidator) MessagePlaceholders

func (v *SizeValidator) MessagePlaceholders(_ *Context) []string

MessagePlaceholders returns the ":value" placeholder.

func (*SizeValidator) Name

func (v *SizeValidator) Name() string

Name returns the string name of the validator.

func (*SizeValidator) Validate

func (v *SizeValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type StartsWithValidator

type StartsWithValidator struct {
	BaseValidator
	Prefix []string
}

StartsWithValidator the field under validation must be a string starting with at least one of the specified prefixes.

func StartsWith

func StartsWith(prefix ...string) *StartsWithValidator

StartsWith the field under validation must be a string starting with at least one of the specified prefixes.

func (*StartsWithValidator) Config

func (c *StartsWithValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*StartsWithValidator) DB

func (c *StartsWithValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*StartsWithValidator) Lang

func (c *StartsWithValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*StartsWithValidator) Logger

func (c *StartsWithValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*StartsWithValidator) MessagePlaceholders

func (v *StartsWithValidator) MessagePlaceholders(_ *Context) []string

MessagePlaceholders returns the ":values" placeholder.

func (*StartsWithValidator) Name

func (v *StartsWithValidator) Name() string

Name returns the string name of the validator.

func (*StartsWithValidator) Validate

func (v *StartsWithValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type StringValidator

type StringValidator struct{ BaseValidator }

StringValidator the field under validation must be a string.

func String

func String() *StringValidator

String the field under validation must be a string.

func (*StringValidator) Config

func (c *StringValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*StringValidator) DB

func (c *StringValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*StringValidator) IsType

func (v *StringValidator) IsType() bool

IsType returns true.

func (*StringValidator) Lang

func (c *StringValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*StringValidator) Logger

func (c *StringValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*StringValidator) Name

func (v *StringValidator) Name() string

Name returns the string name of the validator.

func (*StringValidator) Validate

func (v *StringValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type TimezoneValidator

type TimezoneValidator struct{ BaseValidator }

TimezoneValidator the field under validation must be a valid string reprensentation of a timezone. If validation passes, the value is converted to `*time.Location` using `time.LoadLocation()`. "Local" as an input is not accepted as a valid timezone.

As `time.LoadLocation()` can be a slow operation, timezones are cached.

func Timezone

func Timezone() *TimezoneValidator

Timezone the field under validation must be a valid string reprensentation of a timezone. If validation passes, the value is converted to `*time.Location` using `time.LoadLocation()`. "Local" as an input is not accepted as a valid timezone.

As `time.LoadLocation()` can be a slow operation, timezones are cached.

func (*TimezoneValidator) Config

func (c *TimezoneValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*TimezoneValidator) DB

func (c *TimezoneValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*TimezoneValidator) IsType

func (v *TimezoneValidator) IsType() bool

IsType returns true.

func (*TimezoneValidator) Lang

func (c *TimezoneValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*TimezoneValidator) Logger

func (c *TimezoneValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*TimezoneValidator) Name

func (v *TimezoneValidator) Name() string

Name returns the string name of the validator.

func (*TimezoneValidator) Validate

func (v *TimezoneValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type TrimValidator

type TrimValidator struct{ BaseValidator }

TrimValidator if the field under validation is a string, trims it using `strings.TrimSpace()`.

func Trim

func Trim() *TrimValidator

Trim if the field under validation is a string, trims it using `strings.TrimSpace()`.

func (*TrimValidator) Config

func (c *TrimValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*TrimValidator) DB

func (c *TrimValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*TrimValidator) Lang

func (c *TrimValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*TrimValidator) Logger

func (c *TrimValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*TrimValidator) Name

func (v *TrimValidator) Name() string

Name returns the string name of the validator.

func (*TrimValidator) Validate

func (v *TrimValidator) Validate(ctx *Context) bool

Validate always returns true. If the field under validation is a string, trims it using `strings.TrimSpace()`.

type URLValidator

type URLValidator struct{ BaseValidator }

URLValidator the field under validation must be a string representing a valid URL as per `url.ParseRequestURI()`. If validation passes, the value is converted to `*url.URL`.

func URL

func URL() *URLValidator

URL the field under validation must be a representing a valid URL as per `url.ParseRequestURI()`. If validation passes, the value is converted to `*url.URL`.

func (*URLValidator) Config

func (c *URLValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*URLValidator) DB

func (c *URLValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*URLValidator) IsType

func (v *URLValidator) IsType() bool

IsType returns true.

func (*URLValidator) Lang

func (c *URLValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*URLValidator) Logger

func (c *URLValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*URLValidator) Name

func (v *URLValidator) Name() string

Name returns the string name of the validator.

func (*URLValidator) Validate

func (v *URLValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type UUIDValidator

type UUIDValidator struct {
	BaseValidator
	AcceptedVersions []uuid.Version
}

UUIDValidator the field under validation must be a string representing a valid UUID. If one or more `accepterVersions` are provided, the parsed UUID must be a UUID of one of these versions. If none are given, all versions are accepted.

If validation passes, the value is converted to `uuid.UUID`.

func UUID

func UUID(acceptedVersions ...uuid.Version) *UUIDValidator

UUID the field under validation must be a string representing a valid UUID. If one or more `accepterVersions` are provided, the parsed UUID must be a UUID of one of these versions. If none are given, all versions are accepted.

If validation passes, the value is converted to `uuid.UUID`.

func (*UUIDValidator) Config

func (c *UUIDValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*UUIDValidator) DB

func (c *UUIDValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*UUIDValidator) IsType

func (v *UUIDValidator) IsType() bool

IsType returns true.

func (*UUIDValidator) Lang

func (c *UUIDValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*UUIDValidator) Logger

func (c *UUIDValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*UUIDValidator) Name

func (v *UUIDValidator) Name() string

Name returns the string name of the validator.

func (*UUIDValidator) Validate

func (v *UUIDValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type Uint16Validator

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

Uint16Validator validator for the "uint16" rule.

func Uint16

func Uint16() *Uint16Validator

Uint16 the field under validation must be a positive integer and fit into Go's `uint16` type. If the source number is a float, the validator makes sure the value is within the range of integers that the float can accurately represent.

Floats are only accepted if they don't have a decimal. Strings that can be converted to the target type are accepted. This rule converts the field to `uint16` if it passes.

func (*Uint16Validator) IsType

func (v *Uint16Validator) IsType() bool

IsType returns true

func (*Uint16Validator) Name

func (v *Uint16Validator) Name() string

func (*Uint16Validator) Validate

func (v *Uint16Validator) Validate(ctx *Context) bool

type Uint32Validator

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

Uint32Validator validator for the "uint32" rule.

func Uint32

func Uint32() *Uint32Validator

Uint32 the field under validation must be a positive integer and fit into Go's `uint32` type. If the source number is a float, the validator makes sure the value is within the range of integers that the float can accurately represent.

Floats are only accepted if they don't have a decimal. Strings that can be converted to the target type are accepted. This rule converts the field to `uint32` if it passes.

func (*Uint32Validator) IsType

func (v *Uint32Validator) IsType() bool

IsType returns true

func (*Uint32Validator) Name

func (v *Uint32Validator) Name() string

func (*Uint32Validator) Validate

func (v *Uint32Validator) Validate(ctx *Context) bool

type Uint64Validator

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

Uint64Validator validator for the "uint64" rule.

func Uint64

func Uint64() *Uint64Validator

Uint64 the field under validation must be a positive integer and fit into Go's `uint64` type. If the source number is a float, the validator makes sure the value is within the range of integers that the float can accurately represent.

Floats are only accepted if they don't have a decimal. Strings that can be converted to the target type are accepted. This rule converts the field to `uint64` if it passes.

func (*Uint64Validator) IsType

func (v *Uint64Validator) IsType() bool

IsType returns true

func (*Uint64Validator) Name

func (v *Uint64Validator) Name() string

func (*Uint64Validator) Validate

func (v *Uint64Validator) Validate(ctx *Context) bool

type Uint8Validator

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

Uint8Validator validator for the "uint8" rule.

func Uint8

func Uint8() *Uint8Validator

Uint8 the field under validation must be a positive integer and fit into Go's `uint8` type. If the source number is a float, the validator makes sure the value is within the range of integers that the float can accurately represent.

Floats are only accepted if they don't have a decimal. Strings that can be converted to the target type are accepted. This rule converts the field to `uint8` if it passes.

func (*Uint8Validator) IsType

func (v *Uint8Validator) IsType() bool

IsType returns true

func (*Uint8Validator) Name

func (v *Uint8Validator) Name() string

func (*Uint8Validator) Validate

func (v *Uint8Validator) Validate(ctx *Context) bool

type UintValidator

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

UintValidator validator for the "uint" rule.

func Uint

func Uint() *UintValidator

Uint the field under validation must be a positive integer and fit into Go's `uint` type. If the source number is a float, the validator makes sure the value is within the range of integers that the float can accurately represent.

Floats are only accepted if they don't have a decimal. Strings that can be converted to the target type are accepted. This rule converts the field to `uint` if it passes.

func (*UintValidator) IsType

func (v *UintValidator) IsType() bool

IsType returns true

func (*UintValidator) Name

func (v *UintValidator) Name() string

func (*UintValidator) Validate

func (v *UintValidator) Validate(ctx *Context) bool

type UniqueArrayValidator

type UniqueArrayValidator[T any] struct {
	ExistsArrayValidator[T]
}

UniqueArrayValidator validates the field under validation must be an array and all of its elements must not already exist. The type `T` is the type of the elements of the array under validation.

This is preferable to use this validation rule on the array instead of `Unique` on each array element because this rule will only execute a single SQL query instead of as many as there are elements in the array.

If provided, the `Transform` function is called on every array element to transform them into a raw expression. For example to transform a number into `(123::int)` for Postgres to prevent some type errors.

func UniqueArray

func UniqueArray[T any](table, column string, transform func(val T) clause.Expr) *UniqueArrayValidator[T]

UniqueArray validates the field under validation must be an array and all of its elements must not already exist. The type `T` is the type of the elements of the array under validation.

This is preferable to use this validation rule on the array instead of `Unique` on each array element because this rule will only execute a single SQL query instead of as many as there are elements in the array.

If provided, the `Transform` function is called on every array element to transform them into a raw expression. For example to transform a number into `(123::int)` for Postgres to prevent some type errors.

func (*UniqueArrayValidator) Config

func (c *UniqueArrayValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*UniqueArrayValidator) DB

func (c *UniqueArrayValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*UniqueArrayValidator) Lang

func (c *UniqueArrayValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*UniqueArrayValidator) Logger

func (c *UniqueArrayValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*UniqueArrayValidator[T]) Name

func (v *UniqueArrayValidator[T]) Name() string

Name returns the string name of the validator.

func (*UniqueArrayValidator[T]) Validate

func (v *UniqueArrayValidator[T]) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type UniqueValidator

type UniqueValidator struct {
	BaseValidator
	Scope func(db *gorm.DB, val any) *gorm.DB
}

UniqueValidator validates the field under validation must have a unique value in database according to the provided database scope. Uniqueness is checked using a COUNT query.

func Unique

func Unique(scope func(db *gorm.DB, val any) *gorm.DB) *UniqueValidator

Unique validates the field under validation must have a unique value in database according to the provided database scope. Uniqueness is checked using a COUNT query.

 v.Unique(func(db *gorm.DB, val any) *gorm.DB {
	return db.Model(&model.User{}).Where(clause.PrimaryKey, val)
 })

 v.Unique(func(db *gorm.DB, val any) *gorm.DB {
	// Unique email excluding the currently authenticated user
	return db.Model(&model.User{}).Where("email", val).Where("email != ?", request.User.(*model.User).Email)
 })

func (*UniqueValidator) Config

func (c *UniqueValidator) Config() *config.Config

Config get the configuration given through the validation Options. Panics if there is none.

func (*UniqueValidator) DB

func (c *UniqueValidator) DB() *gorm.DB

DB get the database instance given through the validation Options. Panics if there is none.

func (*UniqueValidator) Lang

func (c *UniqueValidator) Lang() *lang.Language

Lang get the language given through the validation Options. Panics if there is none.

func (*UniqueValidator) Logger

func (c *UniqueValidator) Logger() *slog.Logger

Logger get the Logger given through the validation Options. Panics if there is none.

func (*UniqueValidator) Name

func (v *UniqueValidator) Name() string

Name returns the string name of the validator.

func (*UniqueValidator) Validate

func (v *UniqueValidator) Validate(ctx *Context) bool

Validate checks the field under validation satisfies this validator's criteria.

type Validator

type Validator interface {
	Composable

	// Validate checks the field under validation satisfies this validator's criteria.
	// If necessary, replaces the `Context.Value` with a converted value (see `IsType()`).
	Validate(ctx *Context) bool

	// Name returns the string name of the validator.
	// This is used to generate the language entry for the
	// validation error message.
	Name() string

	// IsTypeDependent returns true if the validator is type-dependent.
	// Type-dependent validators can be used with different field types
	// (numeric, string, arrays, objects and files) and have a different validation messages
	// depending on the type.
	// The language entry used will be "validation.rules.rulename.type"
	IsTypeDependent() bool

	// IsType returns true if the validator if a type validator.
	// A type validator checks if a field has a certain type
	// and can convert the raw value to a value fitting. For example, the UUID
	// validator is a type validator because it takes a string as input, checks if it's a
	// valid UUID and converts it to a `uuid.UUID`.
	IsType() bool

	// MessagePlaceholders returns an associative slice of placeholders and their replacement.
	// This is use to generate the validation error message. An empty slice can be returned.
	// See `lang.Language.Get()` for more details.
	MessagePlaceholders(ctx *Context) []string
	// contains filtered or unexported methods
}

Validator is a Component validating a field value. A validator should not be re-usable or usable concurrently. They are meant to be scoped to a single field validation in a single request.

Jump to

Keyboard shortcuts

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