validation

package module
v4.3.1 Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2021 License: MIT Imports: 14 Imported by: 1

README

Description

This is a fork of ozzo-validation to return all validation errors found in every field instead just one error per field and also force validation even with empty data. For instructions on how to use refer to the original README

Installation

Run the following command to install the package:

go get github.com/itgelo/ozzo-validation/v4
go get github.com/itgelo/ozzo-validation/v4/is

Validating a Simple Value

For a simple value, such as a string or an integer, you may use validation.Validate() to validate it. For example,

package main

import (
	"fmt"

	"github.com/itgelo/ozzo-validation/v4"
	"github.com/itgelo/ozzo-validation/v4/is"
)

func main() {
	data := "example"
	err := validation.Validate(data,
		validation.Required,        // not empty
		validation.Length(10, 100), // length between 10 and 100
		is.URL,                     // is a valid URL
	)
	fmt.Println(err)
	// Output:
	// the length must be between 10 and 100,must be a valid URL
}

Normally validation Length, URL etc it does not validate if the data is empty. If you still need to validate it you may use .ForceValidateEmpty() to force validate it. For example,

data := ""
err := validation.Validate(data,
	validation.Required,
	validation.Length(10, 100).ForceValidateEmpty(), // force validate
	is.URL.ForceValidateEmpty(),                     // force validate
)
fmt.Println(err)
// Output:
// cannot be blank,the length must be between 10 and 100,must be a valid URL

Documentation

Overview

Package validation provides configurable and extensible rules for validating data of various types.

Example
package main

import (
	"fmt"
	"regexp"

	validation "github.com/itgelo/ozzo-validation/v4"
	"github.com/itgelo/ozzo-validation/v4/is"
)

type Address struct {
	Street string
	City   string
	State  string
	Zip    string
}

type Customer struct {
	Name    string
	Gender  string
	Email   string
	Address Address
}

func (a Address) Validate() error {
	return validation.ValidateStruct(&a,

		validation.Field(&a.Street, validation.Required, validation.Length(5, 50)),

		validation.Field(&a.City, validation.Required, validation.Length(5, 50)),

		validation.Field(&a.State, validation.Required, validation.Match(regexp.MustCompile("^[A-Z]{2}$"))),

		validation.Field(&a.Zip, validation.Required, validation.Match(regexp.MustCompile("^[0-9]{5}$"))),
	)
}

func (c Customer) Validate() error {
	return validation.ValidateStruct(&c,

		validation.Field(&c.Name, validation.Required, validation.Length(5, 20)),

		validation.Field(&c.Gender, validation.In("Female", "Male")),

		validation.Field(&c.Email, validation.Required, is.Email),

		validation.Field(&c.Address),
	)
}

func main() {
	c := Customer{
		Name:  "Qiang Xue",
		Email: "q",
		Address: Address{
			Street: "123 Main Street",
			City:   "Unknown",
			State:  "Virginia",
			Zip:    "12345",
		},
	}

	err := c.Validate()
	fmt.Println(err)
}
Output:

Address: (State: must be in a valid format.); Email: must be a valid email address.
Example (Five)
package main

import (
	"fmt"

	validation "github.com/itgelo/ozzo-validation/v4"
)

func main() {
	type Employee struct {
		Name string
	}

	type Manager struct {
		Employee
		Level int
	}

	m := Manager{}
	err := validation.ValidateStruct(&m,
		validation.Field(&m.Name, validation.Required),
		validation.Field(&m.Level, validation.Required),
	)
	fmt.Println(err)
}
Output:

Level: cannot be blank; Name: cannot be blank.
Example (Four)
package main

import (
	"fmt"
	"regexp"

	validation "github.com/itgelo/ozzo-validation/v4"
	"github.com/itgelo/ozzo-validation/v4/is"
)

type Address struct {
	Street string
	City   string
	State  string
	Zip    string
}

type Customer struct {
	Name    string
	Gender  string
	Email   string
	Address Address
}

func (a Address) Validate() error {
	return validation.ValidateStruct(&a,

		validation.Field(&a.Street, validation.Required, validation.Length(5, 50)),

		validation.Field(&a.City, validation.Required, validation.Length(5, 50)),

		validation.Field(&a.State, validation.Required, validation.Match(regexp.MustCompile("^[A-Z]{2}$"))),

		validation.Field(&a.Zip, validation.Required, validation.Match(regexp.MustCompile("^[0-9]{5}$"))),
	)
}

func (c Customer) Validate() error {
	return validation.ValidateStruct(&c,

		validation.Field(&c.Name, validation.Required, validation.Length(5, 20)),

		validation.Field(&c.Gender, validation.In("Female", "Male")),

		validation.Field(&c.Email, validation.Required, is.Email),

		validation.Field(&c.Address),
	)
}

func main() {
	c := Customer{
		Name:  "Qiang Xue",
		Email: "q",
		Address: Address{
			State: "Virginia",
		},
	}

	err := validation.Errors{
		"name":  validation.Validate(c.Name, validation.Required, validation.Length(5, 20)),
		"email": validation.Validate(c.Name, validation.Required, is.Email),
		"zip":   validation.Validate(c.Address.Zip, validation.Required, validation.Match(regexp.MustCompile("^[0-9]{5}$"))),
	}.Filter()
	fmt.Println(err)
}
Output:

email: must be a valid email address; zip: cannot be blank.
Example (Second)
package main

import (
	"fmt"

	validation "github.com/itgelo/ozzo-validation/v4"
	"github.com/itgelo/ozzo-validation/v4/is"
)

func main() {
	data := "example"
	err := validation.Validate(data,
		validation.Required,       // not empty
		validation.Length(5, 100), // length between 5 and 100
		is.URL,                    // is a valid URL
	)
	fmt.Println(err)
}
Output:

must be a valid URL
Example (Seven)
package main

import (
	"fmt"
	"regexp"

	validation "github.com/itgelo/ozzo-validation/v4"
	"github.com/itgelo/ozzo-validation/v4/is"
)

func main() {
	c := map[string]interface{}{
		"Name":  "Qiang Xue",
		"Email": "q",
		"Address": map[string]interface{}{
			"Street": "123",
			"City":   "Unknown",
			"State":  "Virginia",
			"Zip":    "12345",
		},
	}

	err := validation.Validate(c,
		validation.Map(
			// Name cannot be empty, and the length must be between 5 and 20.
			validation.Key("Name", validation.Required, validation.Length(5, 20)),
			// Email cannot be empty and should be in a valid email format.
			validation.Key("Email", validation.Required, is.Email),
			// Validate Address using its own validation rules
			validation.Key("Address", validation.Map(
				// Street cannot be empty, and the length must between 5 and 50
				validation.Key("Street", validation.Required, validation.Length(5, 50)),
				// City cannot be empty, and the length must between 5 and 50
				validation.Key("City", validation.Required, validation.Length(5, 50)),
				// State cannot be empty, and must be a string consisting of two letters in upper case
				validation.Key("State", validation.Required, validation.Match(regexp.MustCompile("^[A-Z]{2}$"))),
				// State cannot be empty, and must be a string consisting of five digits
				validation.Key("Zip", validation.Required, validation.Match(regexp.MustCompile("^[0-9]{5}$"))),
			)),
		),
	)
	fmt.Println(err)
}
Output:

Address: State: must be in a valid format; Street: the length must be between 5 and 50.; Email: must be a valid email address.
Example (Six)
package main

import (
	"context"
	"errors"
	"fmt"

	validation "github.com/itgelo/ozzo-validation/v4"
)

type contextKey int

func main() {
	key := contextKey(1)
	rule := validation.WithContext(func(ctx context.Context, value interface{}) error {
		s, _ := value.(string)
		if ctx.Value(key) == s {
			return nil
		}
		return errors.New("unexpected value")
	})
	ctx := context.WithValue(context.Background(), key, "good sample")

	err1 := validation.ValidateWithContext(ctx, "bad sample", rule)
	fmt.Println(err1)

	err2 := validation.ValidateWithContext(ctx, "good sample", rule)
	fmt.Println(err2)

}
Output:

unexpected value
<nil>
Example (Third)
package main

import (
	"fmt"
	"regexp"

	validation "github.com/itgelo/ozzo-validation/v4"
)

type Address struct {
	Street string
	City   string
	State  string
	Zip    string
}

func (a Address) Validate() error {
	return validation.ValidateStruct(&a,

		validation.Field(&a.Street, validation.Required, validation.Length(5, 50)),

		validation.Field(&a.City, validation.Required, validation.Length(5, 50)),

		validation.Field(&a.State, validation.Required, validation.Match(regexp.MustCompile("^[A-Z]{2}$"))),

		validation.Field(&a.Zip, validation.Required, validation.Match(regexp.MustCompile("^[0-9]{5}$"))),
	)
}

func main() {
	addresses := []Address{
		{State: "MD", Zip: "12345"},
		{Street: "123 Main St", City: "Vienna", State: "VA", Zip: "12345"},
		{City: "Unknown", State: "NC", Zip: "123"},
	}
	err := validation.Validate(addresses)
	fmt.Println(err)
}
Output:

0: (City: cannot be blank; Street: cannot be blank.); 2: (Street: cannot be blank; Zip: must be in a valid format.).

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrNil is the error that returns when a value is not nil.
	ErrNil = NewError("validation_nil", "must be blank")
	// ErrEmpty is the error that returns when a not nil value is not empty.
	ErrEmpty = NewError("validation_empty", "must be blank")
)
View Source
var (
	// ErrDateInvalid is the error that returns in case of an invalid date.
	ErrDateInvalid = NewError("validation_date_invalid", "must be a valid date")
	// ErrDateOutOfRange is the error that returns in case of an invalid date.
	ErrDateOutOfRange = NewError("validation_date_out_of_range", "the date is out of range")
)
View Source
var (
	// ErrLengthTooLong is the error that returns in case of too long length.
	ErrLengthTooLong = NewError("validation_length_too_long", "the length must be no more than {{.max}}")
	// ErrLengthTooShort is the error that returns in case of too short length.
	ErrLengthTooShort = NewError("validation_length_too_short", "the length must be no less than {{.min}}")
	// ErrLengthInvalid is the error that returns in case of an invalid length.
	ErrLengthInvalid = NewError("validation_length_invalid", "the length must be exactly {{.min}}")
	// ErrLengthOutOfRange is the error that returns in case of out of range length.
	ErrLengthOutOfRange = NewError("validation_length_out_of_range", "the length must be between {{.min}} and {{.max}}")
	// ErrLengthEmptyRequired is the error that returns in case of non-empty value.
	ErrLengthEmptyRequired = NewError("validation_length_empty_required", "the value must be empty")
)
View Source
var (
	// ErrNotMap is the error that the value being validated is not a map.
	ErrNotMap = errors.New("only a map can be validated")

	// ErrKeyWrongType is the error returned in case of an incorrect key type.
	ErrKeyWrongType = NewError("validation_key_wrong_type", "key not the correct type")

	// ErrKeyMissing is the error returned in case of a missing key.
	ErrKeyMissing = NewError("validation_key_missing", "required key is missing")

	// ErrKeyUnexpected is the error returned in case of an unexpected key.
	ErrKeyUnexpected = NewError("validation_key_unexpected", "key not expected")
)
View Source
var (
	// ErrMinGreaterEqualThanRequired is the error that returns when a value is less than a specified threshold.
	ErrMinGreaterEqualThanRequired = NewError("validation_min_greater_equal_than_required", "must be no less than {{.threshold}}")
	// ErrMaxLessEqualThanRequired is the error that returns when a value is greater than a specified threshold.
	ErrMaxLessEqualThanRequired = NewError("validation_max_less_equal_than_required", "must be no greater than {{.threshold}}")
	// ErrMinGreaterThanRequired is the error that returns when a value is less than or equal to a specified threshold.
	ErrMinGreaterThanRequired = NewError("validation_min_greater_than_required", "must be greater than {{.threshold}}")
	// ErrMaxLessThanRequired is the error that returns when a value is greater than or equal to a specified threshold.
	ErrMaxLessThanRequired = NewError("validation_max_less_than_required", "must be less than {{.threshold}}")
)
View Source
var (
	// ErrRequired is the error that returns when a value is required.
	ErrRequired = NewError("validation_required", "cannot be blank")
	// ErrNilOrNotEmpty is the error that returns when a value is not nil and is empty.
	ErrNilOrNotEmpty = NewError("validation_nil_or_not_empty_required", "cannot be blank")
)
View Source
var (
	// ErrorTag is the struct tag name used to customize the error field name for a struct field.
	ErrorTag = "json"

	// Skip is a special validation rule that indicates all rules following it should be skipped.
	Skip = skipRule{/* contains filtered or unexported fields */}
)
View Source
var Empty = absentRule{/* contains filtered or unexported fields */}

Empty checks if a not nil value is empty.

View Source
var ErrInInvalid = NewError("validation_in_invalid", "must be a valid value")

ErrInInvalid is the error that returns in case of an invalid value for "in" rule.

View Source
var ErrMatchInvalid = NewError("validation_match_invalid", "must be in a valid format")

ErrMatchInvalid is the error that returns in case of invalid format.

View Source
var ErrMultipleOfInvalid = NewError("validation_multiple_of_invalid", "must be multiple of {{.base}}")

ErrMultipleOfInvalid is the error that returns when a value is not multiple of a base.

View Source
var ErrNotInInvalid = NewError("validation_not_in_invalid", "must not be in list")

ErrNotInInvalid is the error that returns when a value is in a list.

View Source
var ErrNotNilRequired = NewError("validation_not_nil_required", "is required")

ErrNotNilRequired is the error that returns when a value is Nil.

View Source
var (
	// ErrStructPointer is the error that a struct being validated is not specified as a pointer.
	ErrStructPointer = errors.New("only a pointer to a struct can be validated")
)
View Source
var Nil = absentRule{/* contains filtered or unexported fields */}

Nil is a validation rule that checks if a value is nil. It is the opposite of NotNil rule

View Source
var NilOrNotEmpty = RequiredRule{/* contains filtered or unexported fields */}

NilOrNotEmpty checks if a value is a nil pointer or a value that is not empty. NilOrNotEmpty differs from Required in that it treats a nil pointer as valid.

View Source
var NotNil = notNilRule{}

NotNil is a validation rule that checks if a value is not nil. NotNil only handles types including interface, pointer, slice, and map. All other types are considered valid.

View Source
var Required = RequiredRule{/* contains filtered or unexported fields */}

Required is a validation rule that checks if a value is not empty. A value is considered not empty if - integer, float: not zero - bool: true - string, array, slice, map: len() > 0 - interface, pointer: not nil and the referenced value is not empty - any other types

Functions

func EnsureString

func EnsureString(value interface{}) (string, error)

EnsureString ensures the given value is a string. If the value is a byte slice, it will be typecast into a string. An error is returned otherwise.

func Indirect

func Indirect(value interface{}) (interface{}, bool)

Indirect returns the value that the given interface or pointer references to. If the value implements driver.Valuer, it will deal with the value returned by the Value() method instead. A boolean value is also returned to indicate if the value is nil or not (only applicable to interface, pointer, map, and slice). If the value is neither an interface nor a pointer, it will be returned back.

func IsEmpty

func IsEmpty(value interface{}) bool

IsEmpty checks if a value is empty or not. A value is considered empty if - integer, float: zero - bool: false - string, array: len() == 0 - slice, map: nil or len() == 0 - interface, pointer: nil or the referenced value is empty

func IsInternalError

func IsInternalError(err error) bool

IsInternalError returns true if the error is an internal one isntead of a validation error

func IsValidationError

func IsValidationError(err error) bool

IsValidationError returns true if the error returned is a map of strings and errors

func LengthOfValue

func LengthOfValue(value interface{}) (int, error)

LengthOfValue returns the length of a value that is a string, slice, map, or array. An error is returned for all other types.

func StringOrBytes

func StringOrBytes(value interface{}) (isString bool, str string, isBytes bool, bs []byte)

StringOrBytes typecasts a value into a string or byte slice. Boolean flags are returned to indicate if the typecasting succeeds or not.

func ToFloat

func ToFloat(value interface{}) (float64, error)

ToFloat converts the given value to a float64. An error is returned for all incompatible types.

func ToInt

func ToInt(value interface{}) (int64, error)

ToInt converts the given value to an int64. An error is returned for all incompatible types.

func ToUint

func ToUint(value interface{}) (uint64, error)

ToUint converts the given value to an uint64. An error is returned for all incompatible types.

func Validate

func Validate(value interface{}, rules ...Rule) error

Validate validates the given value and returns the validation error, if any.

Validate performs validation using the following steps:

  1. For each rule, call its `Validate()` to validate the value. Return if any error is found.
  2. If the value being validated implements `Validatable`, call the value's `Validate()`. Return with the validation result.
  3. If the value being validated is a map/slice/array, and the element type implements `Validatable`, for each element call the element value's `Validate()`. Return with the validation result.

func ValidateStruct

func ValidateStruct(structPtr interface{}, fields ...*FieldRules) error

ValidateStruct validates a struct by checking the specified struct fields against the corresponding validation rules. Note that the struct being validated must be specified as a pointer to it. If the pointer is nil, it is considered valid. Use Field() to specify struct fields that need to be validated. Each Field() call specifies a single field which should be specified as a pointer to the field. A field can be associated with multiple rules. For example,

value := struct {
    Name  string
    Value string
}{"name", "demo"}
err := validation.ValidateStruct(&value,
    validation.Field(&a.Name, validation.Required),
    validation.Field(&a.Value, validation.Required, validation.Length(5, 10)),
)
fmt.Println(err)
// Value: the length must be between 5 and 10.

An error will be returned if validation fails.

func ValidateStructWithContext

func ValidateStructWithContext(ctx context.Context, structPtr interface{}, fields ...*FieldRules) error

ValidateStructWithContext validates a struct with the given context. The only difference between ValidateStructWithContext and ValidateStruct is that the former will validate struct fields with the provided context. Please refer to ValidateStruct for the detailed instructions on how to use this function.

func ValidateWithContext

func ValidateWithContext(ctx context.Context, value interface{}, rules ...Rule) error

ValidateWithContext validates the given value with the given context and returns the validation error, if any.

ValidateWithContext performs validation using the following steps:

  1. For each rule, call its `ValidateWithContext()` to validate the value if the rule implements `RuleWithContext`. Otherwise call `Validate()` of the rule. Return if any error is found.
  2. If the value being validated implements `ValidatableWithContext`, call the value's `ValidateWithContext()` and return with the validation result.
  3. If the value being validated implements `Validatable`, call the value's `Validate()` and return with the validation result.
  4. If the value being validated is a map/slice/array, and the element type implements `ValidatableWithContext`, for each element call the element value's `ValidateWithContext()`. Return with the validation result.
  5. If the value being validated is a map/slice/array, and the element type implements `Validatable`, for each element call the element value's `Validate()`. Return with the validation result.

Types

type DateRule

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

DateRule is a validation rule that validates date/time string values.

func Date

func Date(layout string) DateRule

Date returns a validation rule that checks if a string value is in a format that can be parsed into a date. The format of the date should be specified as the layout parameter which accepts the same value as that for time.Parse. For example,

validation.Date(time.ANSIC)
validation.Date("02 Jan 06 15:04 MST")
validation.Date("2006-01-02")

By calling Min() and/or Max(), you can let the Date rule to check if a parsed date value is within the specified date range.

An empty value is considered valid. Use the Required rule to make sure a value is not empty.

func (DateRule) Error

func (r DateRule) Error(message string) DateRule

Error sets the error message that is used when the value being validated is not a valid date.

func (DateRule) ErrorObject

func (r DateRule) ErrorObject(err Error) DateRule

ErrorObject sets the error struct that is used when the value being validated is not a valid date..

func (DateRule) ForceValidateEmpty

func (r DateRule) ForceValidateEmpty() DateRule

ForceValidateEmpty force validation even when data is empty.

func (DateRule) Max

func (r DateRule) Max(max time.Time) DateRule

Max sets the maximum date range. A zero value means skipping the maximum range validation.

func (DateRule) Min

func (r DateRule) Min(min time.Time) DateRule

Min sets the minimum date range. A zero value means skipping the minimum range validation.

func (DateRule) RangeError

func (r DateRule) RangeError(message string) DateRule

RangeError sets the error message that is used when the value being validated is out of the specified Min/Max date range.

func (DateRule) RangeErrorObject

func (r DateRule) RangeErrorObject(err Error) DateRule

RangeErrorObject sets the error struct that is used when the value being validated is out of the specified Min/Max date range.

func (DateRule) Validate

func (r DateRule) Validate(value interface{}) error

Validate checks if the given value is a valid date.

type EachRule

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

EachRule is a validation rule that validates elements in a map/slice/array using the specified list of rules.

func Each

func Each(rules ...Rule) EachRule

Each returns a validation rule that loops through an iterable (map, slice or array) and validates each value inside with the provided rules. An empty iterable is considered valid. Use the Required rule to make sure the iterable is not empty.

func (EachRule) Validate

func (r EachRule) Validate(value interface{}) error

Validate loops through the given iterable and calls the Ozzo Validate() method for each value.

func (EachRule) ValidateWithContext

func (r EachRule) ValidateWithContext(ctx context.Context, value interface{}) error

ValidateWithContext loops through the given iterable and calls the Ozzo ValidateWithContext() method for each value.

type ErrFieldNotFound

type ErrFieldNotFound int

ErrFieldNotFound is the error that a field cannot be found in the struct.

func (ErrFieldNotFound) Error

func (e ErrFieldNotFound) Error() string

Error returns the error string of ErrFieldNotFound.

type ErrFieldPointer

type ErrFieldPointer int

ErrFieldPointer is the error that a field is not specified as a pointer.

func (ErrFieldPointer) Error

func (e ErrFieldPointer) Error() string

Error returns the error string of ErrFieldPointer.

type Error

type Error interface {
	Error() string
	Code() string
	Message() string
	SetMessage(string) Error
	Params() map[string]interface{}
	SetParams(map[string]interface{}) Error
}

Error interface represents an validation error

func NewError

func NewError(code, message string) Error

NewError create new validation error.

type ErrorList

type ErrorList []error

ErrorList represents a list of validation errors of a field

func (ErrorList) Error

func (el ErrorList) Error() string

type ErrorObject

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

ErrorObject is the default validation error that implements the Error interface.

func (ErrorObject) AddParam

func (e ErrorObject) AddParam(name string, value interface{}) Error

AddParam add parameter to the error's parameters.

func (ErrorObject) Code

func (e ErrorObject) Code() string

Code get the error's translation code.

func (ErrorObject) Error

func (e ErrorObject) Error() string

Error returns the error message.

func (ErrorObject) Message

func (e ErrorObject) Message() string

Message return the error's message.

func (ErrorObject) Params

func (e ErrorObject) Params() map[string]interface{}

Params returns the error's params.

func (ErrorObject) SetCode

func (e ErrorObject) SetCode(code string) Error

SetCode set the error's translation code.

func (ErrorObject) SetMessage

func (e ErrorObject) SetMessage(message string) Error

SetMessage set the error's message.

func (ErrorObject) SetParams

func (e ErrorObject) SetParams(params map[string]interface{}) Error

SetParams set the error's params.

type Errors

type Errors map[string]error

Errors represents the validation errors that are indexed by struct field names, map or slice keys. values are Error or Errors (for map, slice and array error value is Errors).

func (Errors) Error

func (es Errors) Error() string

Error returns the error string of Errors.

func (Errors) Filter

func (es Errors) Filter() error

Filter removes all nils from Errors and returns back the updated Errors as an error. If the length of Errors becomes 0, it will return nil.

func (Errors) MarshalJSON

func (es Errors) MarshalJSON() ([]byte, error)

MarshalJSON converts the Errors into a valid JSON.

type FieldRules

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

FieldRules represents a rule set associated with a struct field.

func Field

func Field(fieldPtr interface{}, rules ...Rule) *FieldRules

Field specifies a struct field and the corresponding validation rules. The struct field must be specified as a pointer to it.

type InRule

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

InRule is a validation rule that validates if a value can be found in the given list of values.

func In

func In(values ...interface{}) InRule

In returns a validation rule that checks if a value can be found in the given list of values. reflect.DeepEqual() will be used to determine if two values are equal. For more details please refer to https://golang.org/pkg/reflect/#DeepEqual An empty value is considered valid. Use the Required rule to make sure a value is not empty.

func (InRule) Error

func (r InRule) Error(message string) InRule

Error sets the error message for the rule.

func (InRule) ErrorObject

func (r InRule) ErrorObject(err Error) InRule

ErrorObject sets the error struct for the rule.

func (InRule) ForceValidateEmpty

func (r InRule) ForceValidateEmpty() InRule

ForceValidateEmpty force validation even when data is empty.

func (InRule) Validate

func (r InRule) Validate(value interface{}) error

Validate checks if the given value is valid or not.

type InternalError

type InternalError interface {
	error
	InternalError() error
}

InternalError represents an error that should NOT be treated as a validation error.

func NewInternalError

func NewInternalError(err error) InternalError

NewInternalError wraps a given error into an InternalError.

type KeyRules

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

KeyRules represents a rule set associated with a map key.

func Key

func Key(key interface{}, rules ...Rule) *KeyRules

Key specifies a map key and the corresponding validation rules.

func (*KeyRules) Optional

func (r *KeyRules) Optional() *KeyRules

Optional configures the rule to ignore the key if missing.

type LengthRule

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

LengthRule is a validation rule that checks if a value's length is within the specified range.

func Length

func Length(min, max int) LengthRule

Length returns a validation rule that checks if a value's length is within the specified range. If max is 0, it means there is no upper bound for the length. This rule should only be used for validating strings, slices, maps, and arrays. An empty value is considered valid. Use the Required rule to make sure a value is not empty.

func RuneLength

func RuneLength(min, max int) LengthRule

RuneLength returns a validation rule that checks if a string's rune length is within the specified range. If max is 0, it means there is no upper bound for the length. This rule should only be used for validating strings, slices, maps, and arrays. An empty value is considered valid. Use the Required rule to make sure a value is not empty. If the value being validated is not a string, the rule works the same as Length.

func (LengthRule) Error

func (r LengthRule) Error(message string) LengthRule

Error sets the error message for the rule.

func (LengthRule) ErrorObject

func (r LengthRule) ErrorObject(err Error) LengthRule

ErrorObject sets the error struct for the rule.

func (LengthRule) ForceValidateEmpty

func (r LengthRule) ForceValidateEmpty() LengthRule

ForceValidateEmpty force validation even when data is empty.

func (LengthRule) Validate

func (r LengthRule) Validate(value interface{}) error

Validate checks if the given value is valid or not.

type MapRule

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

MapRule represents a rule set associated with a map.

func Map

func Map(keys ...*KeyRules) MapRule

Map returns a validation rule that checks the keys and values of a map. This rule should only be used for validating maps, or a validation error will be reported. Use Key() to specify map keys that need to be validated. Each Key() call specifies a single key which can be associated with multiple rules. For example,

validation.Map(
    validation.Key("Name", validation.Required),
    validation.Key("Value", validation.Required, validation.Length(5, 10)),
)

A nil value is considered valid. Use the Required rule to make sure a map value is present.

func (MapRule) AllowExtraKeys

func (r MapRule) AllowExtraKeys() MapRule

AllowExtraKeys configures the rule to ignore extra keys.

func (MapRule) Validate

func (r MapRule) Validate(m interface{}) error

Validate checks if the given value is valid or not.

func (MapRule) ValidateWithContext

func (r MapRule) ValidateWithContext(ctx context.Context, m interface{}) error

ValidateWithContext checks if the given value is valid or not.

type MatchRule

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

MatchRule is a validation rule that checks if a value matches the specified regular expression.

func Match

func Match(re *regexp.Regexp) MatchRule

Match returns a validation rule that checks if a value matches the specified regular expression. This rule should only be used for validating strings and byte slices, or a validation error will be reported. An empty value is considered valid. Use the Required rule to make sure a value is not empty.

func (MatchRule) Error

func (r MatchRule) Error(message string) MatchRule

Error sets the error message for the rule.

func (MatchRule) ErrorObject

func (r MatchRule) ErrorObject(err Error) MatchRule

ErrorObject sets the error struct for the rule.

func (MatchRule) Validate

func (r MatchRule) Validate(value interface{}) error

Validate checks if the given value is valid or not.

type MultipleOfRule

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

MultipleOfRule is a validation rule that checks if a value is a multiple of the "base" value.

func MultipleOf

func MultipleOf(base interface{}) MultipleOfRule

MultipleOf returns a validation rule that checks if a value is a multiple of the "base" value. Note that "base" should be of integer type.

func (MultipleOfRule) Error

func (r MultipleOfRule) Error(message string) MultipleOfRule

Error sets the error message for the rule.

func (MultipleOfRule) ErrorObject

func (r MultipleOfRule) ErrorObject(err Error) MultipleOfRule

ErrorObject sets the error struct for the rule.

func (MultipleOfRule) Validate

func (r MultipleOfRule) Validate(value interface{}) error

Validate checks if the value is a multiple of the "base" value.

type NotInRule

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

NotInRule is a validation rule that checks if a value is absent from the given list of values.

func NotIn

func NotIn(values ...interface{}) NotInRule

NotIn returns a validation rule that checks if a value is absent from the given list of values. Note that the value being checked and the possible range of values must be of the same type. An empty value is considered valid. Use the Required rule to make sure a value is not empty.

func (NotInRule) Error

func (r NotInRule) Error(message string) NotInRule

Error sets the error message for the rule.

func (NotInRule) ErrorObject

func (r NotInRule) ErrorObject(err Error) NotInRule

ErrorObject sets the error struct for the rule.

func (NotInRule) ForceValidateEmpty

func (r NotInRule) ForceValidateEmpty() NotInRule

ForceValidateEmpty force validation even when data is empty.

func (NotInRule) Validate

func (r NotInRule) Validate(value interface{}) error

Validate checks if the given value is valid or not.

type RequiredRule

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

RequiredRule is a rule that checks if a value is not empty.

func (RequiredRule) Error

func (r RequiredRule) Error(message string) RequiredRule

Error sets the error message for the rule.

func (RequiredRule) ErrorObject

func (r RequiredRule) ErrorObject(err Error) RequiredRule

ErrorObject sets the error struct for the rule.

func (RequiredRule) Validate

func (r RequiredRule) Validate(value interface{}) error

Validate checks if the given value is valid or not.

func (RequiredRule) When

func (r RequiredRule) When(condition bool) RequiredRule

When sets the condition that determines if the validation should be performed.

type Rule

type Rule interface {
	// Validate validates a value and returns a value if validation fails.
	Validate(value interface{}) error
}

Rule represents a validation rule.

func By

func By(f RuleFunc) Rule

By wraps a RuleFunc into a Rule.

func WithContext

func WithContext(f RuleWithContextFunc) Rule

WithContext wraps a RuleWithContextFunc into a context-aware Rule.

type RuleFunc

type RuleFunc func(value interface{}) error

RuleFunc represents a validator function. You may wrap it as a Rule by calling By().

type RuleWithContext

type RuleWithContext interface {
	// ValidateWithContext validates a value and returns a value if validation fails.
	ValidateWithContext(ctx context.Context, value interface{}) error
}

RuleWithContext represents a context-aware validation rule.

type RuleWithContextFunc

type RuleWithContextFunc func(ctx context.Context, value interface{}) error

RuleWithContextFunc represents a validator function that is context-aware. You may wrap it as a Rule by calling WithContext().

type StringRule

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

StringRule is a rule that checks a string variable using a specified stringValidator.

func NewStringRule

func NewStringRule(validator stringValidator, message string) StringRule

NewStringRule creates a new validation rule using a function that takes a string value and returns a bool. The rule returned will use the function to check if a given string or byte slice is valid or not. An empty value is considered to be valid. Please use the Required rule to make sure a value is not empty.

func NewStringRuleWithError

func NewStringRuleWithError(validator stringValidator, err Error) StringRule

NewStringRuleWithError creates a new validation rule using a function that takes a string value and returns a bool. The rule returned will use the function to check if a given string or byte slice is valid or not. An empty value is considered to be valid. Please use the Required rule to make sure a value is not empty.

func (StringRule) Error

func (r StringRule) Error(message string) StringRule

Error sets the error message for the rule.

func (StringRule) ErrorObject

func (r StringRule) ErrorObject(err Error) StringRule

ErrorObject sets the error struct for the rule.

func (StringRule) ForceValidateEmpty

func (r StringRule) ForceValidateEmpty() StringRule

ForceValidateEmpty force validation even when data is empty.

func (StringRule) Validate

func (r StringRule) Validate(value interface{}) error

Validate checks if the given value is valid or not.

type ThresholdRule

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

ThresholdRule is a validation rule that checks if a value satisfies the specified threshold requirement.

func Max

func Max(max interface{}) ThresholdRule

Max returns a validation rule that checks if a value is less or equal than the specified value. By calling Exclusive, the rule will check if the value is strictly less than the specified value. Note that the value being checked and the threshold value must be of the same type. Only int, uint, float and time.Time types are supported. An empty value is considered valid. Please use the Required rule to make sure a value is not empty.

func Min

func Min(min interface{}) ThresholdRule

Min returns a validation rule that checks if a value is greater or equal than the specified value. By calling Exclusive, the rule will check if the value is strictly greater than the specified value. Note that the value being checked and the threshold value must be of the same type. Only int, uint, float and time.Time types are supported. An empty value is considered valid. Please use the Required rule to make sure a value is not empty.

func (ThresholdRule) Error

func (r ThresholdRule) Error(message string) ThresholdRule

Error sets the error message for the rule.

func (ThresholdRule) ErrorObject

func (r ThresholdRule) ErrorObject(err Error) ThresholdRule

ErrorObject sets the error struct for the rule.

func (ThresholdRule) Exclusive

func (r ThresholdRule) Exclusive() ThresholdRule

Exclusive sets the comparison to exclude the boundary value.

func (ThresholdRule) ForceValidateEmpty

func (r ThresholdRule) ForceValidateEmpty() ThresholdRule

ForceValidateEmpty force validation even when data is empty.

func (ThresholdRule) Validate

func (r ThresholdRule) Validate(value interface{}) error

Validate checks if the given value is valid or not.

type Validatable

type Validatable interface {
	// Validate validates the data and returns an error if validation fails.
	Validate() error
}

Validatable is the interface indicating the type implementing it supports data validation.

type ValidatableWithContext

type ValidatableWithContext interface {
	// ValidateWithContext validates the data with the given context and returns an error if validation fails.
	ValidateWithContext(ctx context.Context) error
}

ValidatableWithContext is the interface indicating the type implementing it supports context-aware data validation.

type WhenRule

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

WhenRule is a validation rule that executes the given list of rules when the condition is true.

func When

func When(condition bool, rules ...Rule) WhenRule

When returns a validation rule that executes the given list of rules when the condition is true.

func (WhenRule) Else

func (r WhenRule) Else(rules ...Rule) WhenRule

Else returns a validation rule that executes the given list of rules when the condition is false.

func (WhenRule) Validate

func (r WhenRule) Validate(value interface{}) error

Validate checks if the condition is true and if so, it validates the value using the specified rules.

func (WhenRule) ValidateWithContext

func (r WhenRule) ValidateWithContext(ctx context.Context, value interface{}) error

ValidateWithContext checks if the condition is true and if so, it validates the value using the specified rules.

Directories

Path Synopsis
Package is provides a list of commonly used string validation rules.
Package is provides a list of commonly used string validation rules.

Jump to

Keyboard shortcuts

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