validation

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2024 License: MIT Imports: 21 Imported by: 2

README

Go Version GoDoc Build Status Coverage Status GoReport

Fast and intuitive validation library for Go

This lib uses the Is... validation functions from the govalidator project.

Installation

go get github.com/tiendc/go-validator

Usage

General usage
    import (
        vld "github.com/tiendc/go-validator"
    )

    type Person struct {
        FirstName string
        LastName  string
        Birthdate time.Time

        Unemployed bool
        Salary     uint
        Rank       string
        WorkEmail  string
        Projects   []string
        TaskMap    map[string]Task
    }
    var p Person

    errs := vld.Validate(
        // Validate first and last names separately
        vld.StrLen(&p.FirstName, 3, 30).OnError(
            vld.SetField("first_name", nil),
            vld.SetCustomKey("ERR_VLD_PERSON_FIRST_NAME_INVALID"),
        ),
        vld.StrLen(&p.FirstName, 3, 30).OnError(
            vld.SetField("last_name", nil),
            vld.SetCustomKey("ERR_VLD_PERSON_LAST_NAME_INVALID"),
        ),

        // OR use this to produce only one error when one of them fails
        vld.Group(
            vld.StrLen(&p.FirstName, 3, 30),
            vld.StrLen(&p.LastName, 3, 30),
        ).OnError(
            vld.SetField("name", nil),
            vld.SetCustomKey("ERR_VLD_PERSON_NAME_INVALID"),
        ),

        // Birthdate is optional, but when it's present, it must be within 1950 and now
        vld.When(!p.Birthdate.IsZero()).Then(
            vld.TimeRange(p.Birthdate, <1950-01-01>, time.Now()).OnError(...),
        )

        vld.When(!p.Unemployed).Then(
            vld.Required(&p.Salary),
            // Work email must be valid
            vld.StrIsEmail(&p.WorkEmail),

            // Rank must be one of the constants
            vld.StrIn(&p.Rank, "Employee", "Manager", "Director"),
            vld.Case(
                vld.When(p.Rank == "Manager").Then(vld.NumGT(&p.Salary, 10000)),
                vld.When(p.Rank == "Director").Then(vld.NumGT(&p.Salary, 30000)),
            ).Default(
                vld.NumLT(&p.Salary, 10000),
            ),

            // Projects are optional, but when they are present, they must be unique and sorted
            vld.When(len(p.Projects) > 0).Then(
                vld.SliceUnique(p.Projects).OnError(...),
                vld.SliceSorted(p.Projects).OnError(...),
            )
        ).Else(
            // When person is unemployed
            vld.NumEQ(&p.Salary, 0),
            vld.StrEQ(&p.WorkEmail, ""),
        ),

        // Validate slice elements
        vld.Slice(p.Projects).ForEach(func(elem int, index int, validator ItemValidator) {
            validator.Validate(
                vld.StrLen(&elem, 10, 30).OnError(
                    vld.SetField(fmt.Sprintf("projects[%d]", index), nil),
                    vld.SetCustomKey("ERR_VLD_PROJECT_NAME_INVALID"),
                ),
            )
        }),

        // Validate map entries
        vld.Map(p.TaskMap).ForEach(func(k string, v Task, validator ItemValidator) {
            validator.Validate(
                vld.StrLen(&v.Name, 10, 30).OnError(
                    vld.SetField(fmt.Sprintf("taskMap[%s].name", k), nil),
                    vld.SetCustomKey("ERR_VLD_TASK_NAME_INVALID"),
                ),
            )
        }),

        // OTHER FUNCTIONS
        // Pass if at least one of the validations passes
        vld.OneOf(
            // List of validations
        ),

        // Pass if exact one of the validations passes
        vld.ExactOneOf(
            // List of validations
        ),

        // Pass if none of the validations passes
        vld.NotOf(
            // List of validations
        ),
    )

    for _, e := range errs {
        detail, warnErr := e.BuildDetail()
        fmt.Printf("%+v\n", detail)
    }
Error message localization
  • Method 1: inline localization (not recommended)
    errs := Validate(
        NumLTE(&p.Age, 40).OnError(
            // Override the default template in english
            SetTemplate("Tuổi nhân viên phải nhỏ hơn hoặc bằng {{.Max}}"),
        ),
    )

    for _, e := range errs {
        detail, warnErr := e.BuildDetail()
        fmt.Printf("%+v\n", detail)
    }
  • Method 2: using another localization lib (recommended)
    // Supposed you have 2 files defining error messages
    // In `error_messages.en`:
    // ERR_VLD_EMPLOYEE_AGE_TOO_BIG = "Employee {{.EmployeeName}} has age bigger than {{.Max}}"
    // In `error_messages.vi`:
    // ERR_VLD_EMPLOYEE_AGE_TOO_BIG = "Nhân viên {{.EmployeeName}} có tuổi lớn hơn {{.Max}}"

    errs := Validate(
        NumLTE(&p.Age, 40).OnError(
            // Custom param (the default template doesn't have this one)
            SetParam("EmployeeName", p.Name),
            // Custom key to define custom template to use
            SetCustomKey("ERR_VLD_EMPLOYEE_AGE_TOO_BIG"),
        ),
    )

    for _, e := range errs {
        errKey := e.CustomKey()
        errParams : = e.Params() // or e.ParamsWithFormatter()
        errorMsg := translationFunction(errKey, errParams) // You need to provide this function
        fmt.Printf("%+v\n", errorMsg)
    }
Custom error param formatter
    errs := Validate(
        NumLT(&budget, 1000000).OnError(
            SetField("Budget", nil),
        ),
    )

    // e.BuildDetail() may produce message `Budget must be less than 1000000`,
    // but you may want a message like: `Budget must be less than 1,000,000`.
    // Let's use a custom formatter

    errs := Validate(
        NumLT(&budget, 1000000).OnError(
            SetField("Budget", nil),
            SetNumParamFormatter(NewDecimalFormatFunc('.', ',', "%f")),
        ),
    )

Contributing

  • You are welcome to make pull requests for new functions and bug fixes.

License

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrTypeUnsupported = errors.New("type unsupported")
	ErrFieldMissing    = errors.New("field missing")
)

Errors can be returned from the lib

Functions

func DefaultLang

func DefaultLang() string

DefaultLang default language used in the template

func SetDefaultLang

func SetDefaultLang(lang string)

SetDefaultLang set default language used in the template

func SetTemplateProvider

func SetTemplateProvider(lang string, provider TemplateProvider)

SetTemplateProvider sets current template provider

func ToFloat64

func ToFloat64[T base.Number](v *T) *float64

ToFloat64 transforms a number to float64 value

func ToInt64

func ToInt64[T base.Number](v *T) *int64

ToInt64 transforms a number to int64 value

func ToLower

func ToLower[T base.String](v *T) *T

ToLower transforms characters of a string to lowercase

Example: validation.StrIsEmail(validation.ToLower(&req.Email))

func ToUint64

func ToUint64[T base.Number](v *T) *uint64

ToUint64 transforms a number to uint64 value

func ToUpper

func ToUpper[T base.String](v *T) *T

ToUpper transforms characters of a string to uppercase

Types

type CondValidator

type CondValidator interface {
	Validator
	ValidateWithCond(context.Context) (bool, Errors)
}

CondValidator interface represents a validator that performs multiple validations based on specified conditions.

type Error

type Error interface {
	// Type gets type of error
	Type() string
	// SetType sets type of error
	SetType(string) Error

	// Field gets validating field
	Field() *Field
	// SetField sets validating field
	SetField(*Field) Error

	// Value gets validating value
	Value() any
	// SetValue gets validating value
	SetValue(any) Error

	// ValueType gets type of validating value
	ValueType() string
	// SetValueType sets type of validating value
	SetValueType(string) Error

	// Template gets template used to generating error message
	Template() string
	// SetTemplate sets template of error
	SetTemplate(string) Error

	// Params gets params of error
	Params() ErrorParams
	// SetParam sets params of error
	SetParam(k string, v any) Error

	// ParamFormatter formatter is used to format the error params
	// By default it is TypedParamFormatter
	ParamFormatter() ErrorParamFormatter
	// TypedParamFormatter get TypedParamFormatter attached to the error
	// This will return nil when the attached formatter is not a TypedParamFormatter
	TypedParamFormatter() TypedParamFormatter
	// SetParamFormatter sets params formatter of error
	SetParamFormatter(ErrorParamFormatter) Error

	// CustomKey gets custom key of error
	CustomKey() any
	// SetCustomKey sets custom key of error
	SetCustomKey(any) Error

	// BuildDetail builds error detailed message
	BuildDetail() (string, error)
	// ParamsWithFormatter gets params with wrapping by the formatter of the error
	ParamsWithFormatter() ErrorParams

	// String implements fmt.Stringer interface
	// This function calls BuildDetail() without raising error
	// Should use BuildDetail() for more controls on error
	String() string
	// Error implement error interface
	// See String() string
	Error() string

	// Unwrap implements errors.Unwrap
	Unwrap() []error
	// UnwrapAsErrors unwraps the error as `Errors` type
	UnwrapAsErrors() Errors
}

Error is the interface for all validation errors in this lib

func NewError

func NewError() Error

NewError creates a new Error object

type ErrorMod

type ErrorMod func(Error)

ErrorMod function used to modify an `Error` object

func SetBoolParamFormatter

func SetBoolParamFormatter(formatFunc FormatFunc) ErrorMod

SetBoolParamFormatter returns a ErrorMod function to set format function for bools

func SetCustomKey

func SetCustomKey(key any) ErrorMod

SetCustomKey returns a ErrorMod function to set custom key of error

func SetCustomParamFormatter

func SetCustomParamFormatter(formatFunc FormatFunc) ErrorMod

SetCustomParamFormatter returns a ErrorMod function to set custom format function

func SetField

func SetField(name string, parent *Field) ErrorMod

SetField returns a ErrorMod function to set field of error

func SetMapParamFormatter

func SetMapParamFormatter(formatFunc FormatFunc) ErrorMod

SetMapParamFormatter returns a ErrorMod function to set format function for maps

func SetNumParamFormatter

func SetNumParamFormatter(formatFunc FormatFunc) ErrorMod

SetNumParamFormatter returns a ErrorMod function to set format function for numbers

func SetParam

func SetParam(key string, val any) ErrorMod

SetParam returns a ErrorMod function to set a param of error

func SetParamFormatter

func SetParamFormatter(formatter ErrorParamFormatter) ErrorMod

SetParamFormatter returns a ErrorMod function to set params formatter of error

func SetPtrParamFormatter

func SetPtrParamFormatter(formatFunc FormatFunc) ErrorMod

SetPtrParamFormatter returns a ErrorMod function to set format function for pointers

func SetSliceParamFormatter

func SetSliceParamFormatter(formatFunc FormatFunc) ErrorMod

SetSliceParamFormatter returns a ErrorMod function to set format function for slices

func SetStrParamFormatter

func SetStrParamFormatter(formatFunc FormatFunc) ErrorMod

SetStrParamFormatter returns a ErrorMod function to set format function for strings

func SetStructParamFormatter

func SetStructParamFormatter(formatFunc FormatFunc) ErrorMod

SetStructParamFormatter returns a ErrorMod function to set format function for structs

func SetTemplate

func SetTemplate(template string) ErrorMod

SetTemplate returns a ErrorMod function to set template of error

type ErrorParamFormatter

type ErrorParamFormatter interface {
	Format(k string, v any) string
}

ErrorParamFormatter interface represents a formatter of error params

type ErrorParams

type ErrorParams map[string]any

ErrorParams is a map of params specific to each error

type Errors

type Errors []Error

Errors slice type for `Error` objects

func Validate

func Validate(validators ...Validator) Errors

Validate executes given validators to make result.

func ValidateWithCtx added in v0.6.0

func ValidateWithCtx(ctx context.Context, validators ...Validator) Errors

ValidateWithCtx executes given validators with given context.

func (Errors) Error

func (e Errors) Error() string

type Field

type Field struct {
	Name   string
	Parent *Field
}

Field represents a validating field

func NewField

func NewField(name string, parent *Field) *Field

NewField creates a new Field object

func (*Field) Path

func (c *Field) Path(skipRoot bool) []string

func (*Field) PathString

func (c *Field) PathString(skipRoot bool, sep string) string

type FormatFunc

type FormatFunc func(reflect.Value) string

FormatFunc type of format function which produces string from input value

func NewDecimalFormatFunc

func NewDecimalFormatFunc(fractionSep, groupSep byte, floatFmt string) FormatFunc

NewDecimalFormatFunc returns a FormatFunc which can format and group digits of decimal or integer.

For example: '12345' -> '12,345', '12345.6789' -> '12,345.6789' To attach this formatter to Error object:

  • err.TypedParamFormatter().SetNumFormatFunc(NewDecimalFormatFunc('.', ',', "%.2f"))

func NewDecimalNumFormatFunc deprecated

func NewDecimalNumFormatFunc(floatFmt ...string) FormatFunc

NewDecimalNumFormatFunc returns a FormatFunc which groups digits of decimal.

For example: '12345' -> '12,345', '12345.6789' -> '12,345.6789' To attach this formatter to Error object:

  • err.TypedParamFormatter().SetNumFormatFunc(NewDecimalNumFormatFunc())
  • err.TypedParamFormatter().SetNumFormatFunc(NewDecimalNumFormatFunc("%.5f"))

Deprecated: use NewDecimalFormatFunc instead

func NewJSONFormatFunc

func NewJSONFormatFunc() FormatFunc

NewJSONFormatFunc create a format func to format input as JSON output

func NewMapFormatFunc

func NewMapFormatFunc(
	keyFormatFunc, valueFormatFunc FormatFunc,
	leftWrap, rightWrap string, kvSep, entrySep string,
) FormatFunc

NewMapFormatFunc create a new func for formatting a map. Sample arguments: leftWrap "{", rightWrap "}", kvSep ":", elemSep ", "

func NewSliceFormatFunc

func NewSliceFormatFunc(
	elemFormatFunc FormatFunc,
	leftWrap, rightWrap string, elemSep string,
) FormatFunc

NewSliceFormatFunc create a new func for formatting a slice. Sample arguments: leftWrap "[", rightWrap "]", elemSep ", "

type ItemValidator added in v1.0.0

type ItemValidator interface {
	Validate(validators ...Validator)
	Group(validators ...Validator) SingleValidator
	OneOf(validators ...Validator) SingleValidator
	ExactOneOf(validators ...Validator) SingleValidator
	NotOf(validators ...Validator) SingleValidator
}

ItemValidator validator to collect input validators via its Validate() func

type MapContentValidator added in v1.0.0

type MapContentValidator[K comparable, V any, M ~map[K]V] interface {
	Validator
	ForEach(fn func(k K, v V, entryValidator ItemValidator)) MapContentValidator[K, V, M]
}

MapContentValidator validator that validates map entries

func Map added in v1.0.0

func Map[K comparable, V any, M ~map[K]V](m M) MapContentValidator[K, V, M]

Map allows validating every map entry

func NewMapContentValidator added in v1.0.0

func NewMapContentValidator[K comparable, V any, M ~map[K]V](mapObj M) MapContentValidator[K, V, M]

NewMapContentValidator creates a new MapContentValidator

type MultiCondValidator

type MultiCondValidator interface {
	CondValidator
	Default(validators ...Validator) MultiCondValidator
}

MultiCondValidator validator that accepts multiple conditions

func Case

func Case(conditions ...SingleCondValidator) MultiCondValidator

Case works like a `switch...case` statement

func NewMultiCondValidator

func NewMultiCondValidator(conditions ...SingleCondValidator) MultiCondValidator

NewMultiCondValidator creates a new MultiCondValidator

type SingleCondValidator

type SingleCondValidator interface {
	CondValidator
	Then(validators ...Validator) SingleCondValidator
	Else(validators ...Validator) SingleCondValidator
}

SingleCondValidator validator that accepts only one condition

func NewSingleCondValidator

func NewSingleCondValidator(conditions ...any) SingleCondValidator

NewSingleCondValidator creates a new SingleCondValidator

func When

func When(conditions ...any) SingleCondValidator

When works like a `if...then...else` statement

type SingleValidator

type SingleValidator interface {
	Validator
}

SingleValidator interface represents a validator that performs a single validation

func ExactOneOf

func ExactOneOf(validators ...Validator) SingleValidator

ExactOneOf checks if the target value satisfies only one of the given validators. This returns error when there is not one or more than one validator pass.

func Group

func Group(validators ...Validator) SingleValidator

Group groups the given validators into one. In case there are errors, only one error will be returned.

func If

func If(cond bool) SingleValidator

If a bare check validation convenient for validating custom data such as `If(myTime.Before(dueDate)).OnError(vld.SetCustomKey("MY_ERR_KEY"))`. Deprecated: use `Must` instead

func MapHasKey added in v1.2.0

func MapHasKey[K comparable, V any, M ~map[K]V](m M, keys ...K) SingleValidator

MapHasKey validates the input map must have the specified keys

func MapKeyIn

func MapKeyIn[K comparable, V any, M ~map[K]V](m M, keys ...K) SingleValidator

MapKeyIn validates the input map must have keys in the specified values

func MapKeyNotIn

func MapKeyNotIn[K comparable, V any, M ~map[K]V](m M, keys ...K) SingleValidator

MapKeyNotIn validates the input map must have keys not in the specified values

func MapKeyRange

func MapKeyRange[K base.Number | base.String, V any, M ~map[K]V](m M, min, max K) SingleValidator

MapKeyRange validates the input map must have keys in the specified range. Only applies to key type of number or string.

func MapLen

func MapLen[K comparable, V any, M ~map[K]V](m M, min, max int) SingleValidator

MapLen validates the input map must have length in the specified range

func MapNotHaveKey added in v1.2.0

func MapNotHaveKey[K comparable, V any, M ~map[K]V](m M, keys ...K) SingleValidator

MapNotHaveKey validates the input map must not have the specified keys

func MapValueIn

func MapValueIn[K comparable, V comparable, M ~map[K]V](m M, values ...V) SingleValidator

MapValueIn validates the input map must have values in the specified values

func MapValueNotIn

func MapValueNotIn[K comparable, V comparable, M ~map[K]V](m M, values ...V) SingleValidator

MapValueNotIn validates the input map must have values not in the specified values

func MapValueRange

func MapValueRange[K comparable, V base.Number | base.String, M ~map[K]V](m M, min, max V) SingleValidator

MapValueRange validates the input map must have values in the specified range. Only applies to value type of number or string.

func MapValueUnique

func MapValueUnique[K comparable, V comparable, M ~map[K]V](m M) SingleValidator

MapValueUnique validates the input map must have unique values

func Must

func Must(cond bool) SingleValidator

Must a bare check validation convenient for validating custom data such as `Must(myTime.Before(dueDate)).OnError(vld.SetCustomKey("MY_ERR_KEY"))`.

func NewSingleValidator

func NewSingleValidator(execFn func(ctx context.Context) Error) SingleValidator

NewSingleValidator creates a new SingleValidator

func Nil

func Nil[T any](v *T) SingleValidator

Nil validates the input pointer to be `nil`

func NotNil

func NotNil[T any](v *T) SingleValidator

NotNil validates the input pointer to be not `nil`

func NotOf

func NotOf(validators ...Validator) SingleValidator

NotOf checks the target value not satisfy any of the given validators. When a validator passes, an error will be returned and the remaining checks will be skipped.

func NumDivisibleBy

func NumDivisibleBy[T base.Int | base.UInt](v *T, div T) SingleValidator

NumDivisibleBy validates the input number must be divisible by the specified value

func NumEQ

func NumEQ[T base.Number](v *T, val T) SingleValidator

NumEQ validates the input number must equal to a value

func NumGT

func NumGT[T base.Number](v *T, min T) SingleValidator

NumGT validates the input number must be greater than a value

func NumGTE

func NumGTE[T base.Number](v *T, min T) SingleValidator

NumGTE validates the input number must be greater than or equal to a value

func NumIn

func NumIn[T base.Number](v *T, s ...T) SingleValidator

NumIn validates the input number must be in the specified values

func NumJsSafeInt

func NumJsSafeInt[T base.Int | base.UInt](v *T) SingleValidator

NumJsSafeInt validates the input number must be a Javascript safe integer (max 2^53-1)

func NumLT

func NumLT[T base.Number](v *T, max T) SingleValidator

NumLT validates the input number must be less than a value

func NumLTE

func NumLTE[T base.Number](v *T, max T) SingleValidator

NumLTE validates the input number must be less than or equal to a value

func NumNotIn

func NumNotIn[T base.Number](v *T, s ...T) SingleValidator

NumNotIn validates the input number must be not in the specified values

func NumRange

func NumRange[T base.Number](v *T, min, max T) SingleValidator

NumRange validates the input number must be in the specified range

func OneOf

func OneOf(validators ...Validator) SingleValidator

OneOf checks if the target value satisfies one of the given validators. When a validator passes, the remaining ones will be skipped.

func Required

func Required(v any) SingleValidator

Required validates the input to be required. Required value must be not:

  • zero value (0, "", nil, false)
  • empty slice, array, map, channel
  • pointer points to zero value

func SliceElemIn

func SliceElemIn[T comparable, S ~[]T](v S, list ...T) SingleValidator

SliceElemIn validates the input slice must contain items in the specified values

func SliceElemNotIn

func SliceElemNotIn[T comparable, S ~[]T](v S, list ...T) SingleValidator

SliceElemNotIn validates the input slice must contain items not in the specified values

func SliceElemRange

func SliceElemRange[T base.Number | base.String, S ~[]T](v S, min, max T) SingleValidator

SliceElemRange validates the input slice must contain items in the specified range

func SliceHasElem added in v1.2.0

func SliceHasElem[T comparable, S ~[]T](v S, list ...T) SingleValidator

SliceHasElem validates the input slice must contain the specified values

func SliceHasElemBy added in v1.2.0

func SliceHasElemBy[T any, S ~[]T](v S, isExistFn func(T) bool) SingleValidator

SliceHasElemBy validates the input slice must contain certain values using custom function

func SliceLen

func SliceLen[T any, S ~[]T](v S, min, max int) SingleValidator

SliceLen validates the input slice must have length in the specified range

func SliceNotHaveElem added in v1.2.0

func SliceNotHaveElem[T comparable, S ~[]T](v S, list ...T) SingleValidator

SliceNotHaveElem validates the input slice must not contain the specified values

func SliceNotHaveElemBy added in v1.2.0

func SliceNotHaveElemBy[T any, S ~[]T](v S, isExistFn func(T) bool) SingleValidator

SliceNotHaveElemBy validates the input slice must not contain certain values using custom function

func SliceSorted

func SliceSorted[T base.Number | base.String, S ~[]T](v S) SingleValidator

SliceSorted validates the input slice must be sorted in ascending order

func SliceSortedBy added in v1.1.0

func SliceSortedBy[T any, U base.Number | base.String, S ~[]T](v S, keyFn func(T) U) SingleValidator

SliceSortedBy validates the input slice must be sorted in ascending order defined by the key function

func SliceSortedDesc

func SliceSortedDesc[T base.Number | base.String, S ~[]T](v S) SingleValidator

SliceSortedDesc validates the input slice must be sorted in descending order

func SliceSortedDescBy added in v1.1.0

func SliceSortedDescBy[T any, U base.Number | base.String, S ~[]T](v S, keyFn func(T) U) SingleValidator

SliceSortedDescBy validates the input slice must be sorted in ascending order defined by the key function

func SliceUnique

func SliceUnique[T comparable, S ~[]T](v S) SingleValidator

SliceUnique validates the input slice must contain only unique items

func SliceUniqueBy added in v1.1.0

func SliceUniqueBy[T any, U comparable, S ~[]T](v S, keyFn func(T) U) SingleValidator

SliceUniqueBy validates the input slice must contain only unique items

func StrByteLen

func StrByteLen[T base.String](s *T, min, max int) SingleValidator

StrByteLen validates the input string must have length of bytes in the specified range

func StrByteMatch

func StrByteMatch[T base.String](v *T, re *regexp.Regexp) SingleValidator

StrByteMatch validates the input string must have bytes matching the specified regex

func StrEQ

func StrEQ[T base.String](v *T, s T) SingleValidator

StrEQ validates the input string must equal to the specified value

func StrHasLowerCase

func StrHasLowerCase[T base.String](s *T) SingleValidator

StrHasLowerCase validates the input string must contain at least 1 lower case character

func StrHasUpperCase

func StrHasUpperCase[T base.String](s *T) SingleValidator

StrHasUpperCase validates the input string must contain at least 1 upper case character

func StrHasWhitespace

func StrHasWhitespace[T base.String](s *T) SingleValidator

StrHasWhitespace validates the input string must contain at least 1 whitespace character

func StrHasWhitespaceOnly

func StrHasWhitespaceOnly[T base.String](s *T) SingleValidator

StrHasWhitespaceOnly validates the input string must contain whitespaces only

func StrIn

func StrIn[T base.String](v *T, s ...T) SingleValidator

StrIn validates the input string must be in the specified values

func StrIsASCII

func StrIsASCII[T base.String](s *T) SingleValidator

StrIsASCII validates the input string must contain only ASCII characters

func StrIsAlpha

func StrIsAlpha[T base.String](s *T) SingleValidator

StrIsAlpha validates the input string must contain only characters in range a-zA-Z

func StrIsAlphanumeric

func StrIsAlphanumeric[T base.String](s *T) SingleValidator

StrIsAlphanumeric validates the input string must contain only characters in range a-zA-Z0-9

func StrIsBase64

func StrIsBase64[T base.String](s *T) SingleValidator

StrIsBase64 validates the input string must be in Base64 format

func StrIsCIDR

func StrIsCIDR[T base.String](s *T) SingleValidator

StrIsCIDR validates the input string must be in CIDR format

func StrIsCRC32

func StrIsCRC32[T base.String](s *T) SingleValidator

StrIsCRC32 validates the input string must be in CRC32 format

func StrIsCRC32b

func StrIsCRC32b[T base.String](s *T) SingleValidator

StrIsCRC32b validates the input string must be in CRC32b format

func StrIsCreditCard

func StrIsCreditCard[T base.String](s *T) SingleValidator

StrIsCreditCard validates the input string must be a credit card number

func StrIsDNSName

func StrIsDNSName[T base.String](s *T) SingleValidator

StrIsDNSName validates the input string must be a domain name

func StrIsDataURI

func StrIsDataURI[T base.String](s *T) SingleValidator

StrIsDataURI validates the input string must be a data URI

func StrIsDialString

func StrIsDialString[T base.String](s *T) SingleValidator

StrIsDialString validates the input string must be a dial string such as a hostname, IP, or a port

func StrIsE164

func StrIsE164[T base.String](s *T) SingleValidator

StrIsE164 validates the input string must be in E164 format

func StrIsEmail

func StrIsEmail[T base.String](s *T) SingleValidator

StrIsEmail validates the input string must be a valid email

func StrIsExistingEmail

func StrIsExistingEmail[T base.String](s *T) SingleValidator

StrIsExistingEmail validates the input string must be a valid email of existing domain

func StrIsFilePath

func StrIsFilePath[T base.String](s *T) SingleValidator

StrIsFilePath validates the input string must be a file path in both Windows or Unix

func StrIsFloat

func StrIsFloat[T base.String](s *T) SingleValidator

StrIsFloat validates the input string must be a floating number

func StrIsFullWidth

func StrIsFullWidth[T base.String](s *T) SingleValidator

StrIsFullWidth validates the input string must contain only full-width characters

func StrIsHalfWidth

func StrIsHalfWidth[T base.String](s *T) SingleValidator

StrIsHalfWidth validates the input string must contain only half-width characters

func StrIsHexadecimal

func StrIsHexadecimal[T base.String](s *T) SingleValidator

StrIsHexadecimal validates the input string must be in hex format

func StrIsHexcolor

func StrIsHexcolor[T base.String](s *T) SingleValidator

StrIsHexcolor validates the input string must be a hex color such as #fab or #aabbcc

func StrIsHost

func StrIsHost[T base.String](s *T) SingleValidator

StrIsHost validates the input string must be a hostname or an IP

func StrIsIMEI

func StrIsIMEI[T base.String](s *T) SingleValidator

StrIsIMEI validates the input string must be an IMEI

func StrIsIMSI

func StrIsIMSI[T base.String](s *T) SingleValidator

StrIsIMSI validates the input string must be an IMSI

func StrIsIP

func StrIsIP[T base.String](s *T) SingleValidator

StrIsIP validates the input string must be in IP v4 or IP v6 format

func StrIsIPv4

func StrIsIPv4[T base.String](s *T) SingleValidator

StrIsIPv4 validates the input string must be in IP v4 format

func StrIsIPv6

func StrIsIPv6[T base.String](s *T) SingleValidator

StrIsIPv6 validates the input string must be in IP v6 format

func StrIsISBN

func StrIsISBN[T base.String](s *T) SingleValidator

StrIsISBN validates the input string must be a ISBN v10 or ISBN v13

func StrIsISBN10

func StrIsISBN10[T base.String](s *T) SingleValidator

StrIsISBN10 validates the input string must be a ISBN v10

func StrIsISBN13

func StrIsISBN13[T base.String](s *T) SingleValidator

StrIsISBN13 validates the input string must be a ISBN v13

func StrIsISO3166Alpha2

func StrIsISO3166Alpha2[T base.String](s *T) SingleValidator

StrIsISO3166Alpha2 validates the input string must be one of ISO3166 Alpha2 country codes

func StrIsISO3166Alpha3

func StrIsISO3166Alpha3[T base.String](s *T) SingleValidator

StrIsISO3166Alpha3 validates the input string must be one of ISO3166 Alpha3 country codes

func StrIsISO4217

func StrIsISO4217[T base.String](s *T) SingleValidator

StrIsISO4217 validates the input string must be one of ISO4217 currency codes

func StrIsISO639Alpha2

func StrIsISO639Alpha2[T base.String](s *T) SingleValidator

StrIsISO639Alpha2 validates the input string must be one of ISO639 Alpha2 language codes

func StrIsISO639Alpha3b

func StrIsISO639Alpha3b[T base.String](s *T) SingleValidator

StrIsISO639Alpha3b validates the input string must be one of ISO639 Alpha3b language codes

func StrIsInt

func StrIsInt[T base.String](s *T) SingleValidator

StrIsInt validates the input string must be an integral number

func StrIsJSON

func StrIsJSON[T base.String](s *T) SingleValidator

StrIsJSON validates the input string must be in JSON format

func StrIsLatitude

func StrIsLatitude[T base.String](s *T) SingleValidator

StrIsLatitude validates the input string must be a latitude number

func StrIsLongitude

func StrIsLongitude[T base.String](s *T) SingleValidator

StrIsLongitude validates the input string must be a longitude number

func StrIsLowerCase

func StrIsLowerCase[T base.String](s *T) SingleValidator

StrIsLowerCase validates the input string must be in lower case

func StrIsMAC

func StrIsMAC[T base.String](s *T) SingleValidator

StrIsMAC validates the input string must be in MAC address format

func StrIsMD4

func StrIsMD4[T base.String](s *T) SingleValidator

StrIsMD4 validates the input string must be in MD4 format

func StrIsMD5

func StrIsMD5[T base.String](s *T) SingleValidator

StrIsMD5 validates the input string must be in MD5 format

func StrIsMagnetURI

func StrIsMagnetURI[T base.String](s *T) SingleValidator

StrIsMagnetURI validates the input string must be a magnet URI

func StrIsMongoID

func StrIsMongoID[T base.String](s *T) SingleValidator

StrIsMongoID validates the input string must be a Mongo ID

func StrIsMultibyte

func StrIsMultibyte[T base.String](s *T) SingleValidator

StrIsMultibyte validates the input string must be a multiple-byte string

func StrIsNumeric

func StrIsNumeric[T base.String](s *T) SingleValidator

StrIsNumeric validates the input string must contain only characters in range 0-9

func StrIsPort

func StrIsPort[T base.String](s *T) SingleValidator

StrIsPort validates the input string must be a valid port number (range 1-65535)

func StrIsPrintableASCII

func StrIsPrintableASCII[T base.String](s *T) SingleValidator

StrIsPrintableASCII validates the input string must contain only printable ASCII characters

func StrIsRFC3339

func StrIsRFC3339[T base.String](s *T) SingleValidator

StrIsRFC3339 validates the input string must be a date time of RFC3339 layout

func StrIsRFC3339WithoutZone

func StrIsRFC3339WithoutZone[T base.String](s *T) SingleValidator

StrIsRFC3339WithoutZone validates the input string must be a date time of RFC3339 layout without time zone

func StrIsRGBcolor

func StrIsRGBcolor[T base.String](s *T) SingleValidator

StrIsRGBcolor validates the input string must be a rgb color such as rgb(10,20,30)

func StrIsRegex

func StrIsRegex[T base.String](s *T) SingleValidator

StrIsRegex validates the input string must be a regex

func StrIsRequestURI

func StrIsRequestURI[T base.String](s *T) SingleValidator

StrIsRequestURI validates the input string must be a valid request URI

func StrIsRequestURL

func StrIsRequestURL[T base.String](s *T) SingleValidator

StrIsRequestURL validates the input string must be a valid request URL (URL confirm to RFC 3986)

func StrIsRipeMD128

func StrIsRipeMD128[T base.String](s *T) SingleValidator

StrIsRipeMD128 validates the input string must be in RipeMD128 format

func StrIsRipeMD160

func StrIsRipeMD160[T base.String](s *T) SingleValidator

StrIsRipeMD160 validates the input string must be in RipeMD160 format

func StrIsRsaPublicKey

func StrIsRsaPublicKey[T base.String](s *T, keyLen int) SingleValidator

StrIsRsaPublicKey validates the input string must be an RSA public key

func StrIsSHA1

func StrIsSHA1[T base.String](s *T) SingleValidator

StrIsSHA1 validates the input string must be in SHA1 format

func StrIsSHA256

func StrIsSHA256[T base.String](s *T) SingleValidator

StrIsSHA256 validates the input string must be in SHA256 format

func StrIsSHA3224

func StrIsSHA3224[T base.String](s *T) SingleValidator

StrIsSHA3224 validates the input string must be in SHA3-224 format

func StrIsSHA3256

func StrIsSHA3256[T base.String](s *T) SingleValidator

StrIsSHA3256 validates the input string must be in SHA3-256 format

func StrIsSHA3384

func StrIsSHA3384[T base.String](s *T) SingleValidator

StrIsSHA3384 validates the input string must be in SHA3-384 format

func StrIsSHA3512

func StrIsSHA3512[T base.String](s *T) SingleValidator

StrIsSHA3512 validates the input string must be in SHA3-512 format

func StrIsSHA384

func StrIsSHA384[T base.String](s *T) SingleValidator

StrIsSHA384 validates the input string must be in SHA384 format

func StrIsSHA512

func StrIsSHA512[T base.String](s *T) SingleValidator

StrIsSHA512 validates the input string must be in SHA512 format

func StrIsSSN

func StrIsSSN[T base.String](s *T) SingleValidator

StrIsSSN validates the input string must be a SSN

func StrIsSemver

func StrIsSemver[T base.String](s *T) SingleValidator

StrIsSemver validates the input string must be a Semver

func StrIsTiger128

func StrIsTiger128[T base.String](s *T) SingleValidator

StrIsTiger128 validates the input string must be in Tiger128 format

func StrIsTiger160

func StrIsTiger160[T base.String](s *T) SingleValidator

StrIsTiger160 validates the input string must be in Tiger160 format

func StrIsTiger192

func StrIsTiger192[T base.String](s *T) SingleValidator

StrIsTiger192 validates the input string must be in Tiger192 format

func StrIsTime

func StrIsTime[T base.String](s *T, layout string) SingleValidator

StrIsTime validates the input string must be a date time of the specified layout

func StrIsULID

func StrIsULID[T base.String](s *T) SingleValidator

StrIsULID validates the input string must be a ULID

func StrIsURL

func StrIsURL[T base.String](s *T) SingleValidator

StrIsURL validates the input string must be a valid URL

func StrIsUTFDigit

func StrIsUTFDigit[T base.String](s *T) SingleValidator

StrIsUTFDigit validates the input string must contain only UTF digits

func StrIsUTFLetter

func StrIsUTFLetter[T base.String](s *T) SingleValidator

StrIsUTFLetter validates the input string must contain only UTF letters

func StrIsUTFLetterNumeric

func StrIsUTFLetterNumeric[T base.String](s *T) SingleValidator

StrIsUTFLetterNumeric validates the input string must contain only UTF letters and numerics

func StrIsUTFNumeric

func StrIsUTFNumeric[T base.String](s *T) SingleValidator

StrIsUTFNumeric validates the input string must contain only UTF numeric characters

func StrIsUUID

func StrIsUUID[T base.String](s *T) SingleValidator

StrIsUUID validates the input string must be a UUID v3 or UUID v4 or UUID v5

func StrIsUUIDv3

func StrIsUUIDv3[T base.String](s *T) SingleValidator

StrIsUUIDv3 validates the input string must be a UUID v3

func StrIsUUIDv4

func StrIsUUIDv4[T base.String](s *T) SingleValidator

StrIsUUIDv4 validates the input string must be a UUID v4

func StrIsUUIDv5

func StrIsUUIDv5[T base.String](s *T) SingleValidator

StrIsUUIDv5 validates the input string must be a UUID v5

func StrIsUnixFilePath

func StrIsUnixFilePath[T base.String](s *T) SingleValidator

StrIsUnixFilePath validates the input string must be a file path in Unix

func StrIsUnixTime

func StrIsUnixTime[T base.String](s *T) SingleValidator

StrIsUnixTime validates the input string must be a unix time value

func StrIsUpperCase

func StrIsUpperCase[T base.String](s *T) SingleValidator

StrIsUpperCase validates the input string must be in upper case

func StrIsVariableWidth

func StrIsVariableWidth[T base.String](s *T) SingleValidator

StrIsVariableWidth validates the input string must contain variable-width characters

func StrIsWinFilePath

func StrIsWinFilePath[T base.String](s *T) SingleValidator

StrIsWinFilePath validates the input string must be a file path in Windows

func StrLen

func StrLen[T base.String](s *T, min, max int) SingleValidator

StrLen validates the input string must have length of runes in the specified range

func StrMatch

func StrMatch[T base.String](v *T, re *regexp.Regexp) SingleValidator

StrMatch validates the input string must have runes matching the specified regex

func StrNotIn

func StrNotIn[T base.String](v *T, s ...T) SingleValidator

StrNotIn validates the input string must be not in the specified values

func TimeEQ

func TimeEQ[T base.Time](v T, val time.Time) SingleValidator

TimeEQ validates the input time must equal to the specified value

func TimeGT

func TimeGT[T base.Time](v T, min time.Time) SingleValidator

TimeGT validates the input time must be greater than the specified value

func TimeGTE

func TimeGTE[T base.Time](v T, min time.Time) SingleValidator

TimeGTE validates the input time must be greater than or equal to the specified value

func TimeIn

func TimeIn[T base.Time](v T, s ...time.Time) SingleValidator

TimeIn validates the input time must be in the specified values

func TimeLT

func TimeLT[T base.Time](v T, max time.Time) SingleValidator

TimeLT validates the input time must be less than the specified value

func TimeLTE

func TimeLTE[T base.Time](v T, max time.Time) SingleValidator

TimeLTE validates the input time must be less than or equal to the specified value

func TimeNotIn

func TimeNotIn[T base.Time](v T, s ...time.Time) SingleValidator

TimeNotIn validates the input time must be not in the specified values

func TimeRange

func TimeRange[T base.Time](v T, min, max time.Time) SingleValidator

TimeRange validates the input time must be in the specified range

func TimeValid

func TimeValid[T base.Time](v T) SingleValidator

TimeValid validates the input time must be not zero value

type SliceContentValidator added in v1.0.0

type SliceContentValidator[T any, S ~[]T] interface {
	Validator
	ForEach(fn func(element T, index int, elemValidator ItemValidator)) SliceContentValidator[T, S]
}

SliceContentValidator validator that validates slice elements

func NewSliceContentValidator added in v1.0.0

func NewSliceContentValidator[T any, S ~[]T](slice S) SliceContentValidator[T, S]

NewSliceContentValidator creates a new SliceContentValidator

func Slice added in v1.0.0

func Slice[T any, S ~[]T](s S) SliceContentValidator[T, S]

Slice allows validating slice elements

type TemplateProvider

type TemplateProvider interface {
	Get(Error) string
}

TemplateProvider interface for providing template for generating error messages

func GetTemplateProvider

func GetTemplateProvider(lang string) TemplateProvider

GetTemplateProvider gets current template provider

type TypedParamFormatter

type TypedParamFormatter interface {
	ErrorParamFormatter

	// SetNumFormatFunc set format function for numbers
	SetNumFormatFunc(FormatFunc)
	// SetStrFormatFunc set format function for strings
	SetStrFormatFunc(FormatFunc)
	// SetBoolFormatFunc set format function for bools
	SetBoolFormatFunc(FormatFunc)
	// SetSliceFormatFunc set format function for slices
	SetSliceFormatFunc(FormatFunc)
	// SetMapFormatFunc set format function for maps
	SetMapFormatFunc(FormatFunc)
	// SetStructFormatFunc set format function for structs
	SetStructFormatFunc(FormatFunc)
	// SetPtrFormatFunc set format function for pointers
	SetPtrFormatFunc(FormatFunc)
	// SetCustomFormatFunc set custom format function
	SetCustomFormatFunc(FormatFunc)
}

TypedParamFormatter interface of param formatter which consists of a set of format functions for common Go value types.

func NewTypedParamFormatter

func NewTypedParamFormatter() TypedParamFormatter

NewTypedParamFormatter creates a new TypedParamFormatter with using default format functions

type Validator

type Validator interface {
	Validate(context.Context) Errors
	OnError(...ErrorMod) Validator
}

Validator interface represents a validator object

Directories

Path Synopsis
map
internal

Jump to

Keyboard shortcuts

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