ozzo-validation: github.com/go-ozzo/ozzo-validation Index | Examples | Files | Directories

package validation

import "github.com/go-ozzo/ozzo-validation"

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

Code:

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.

Code:

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.

Code:

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.

Code:

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

Code:

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>

Code:

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

Package Files

date.go each.go error.go in.go length.go match.go minmax.go multipleof.go not_in.go not_nil.go required.go string.go struct.go util.go validation.go

Variables

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{}
)
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")
)
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.

var NotNil = notNilRule{/* contains filtered or unexported fields */}

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.

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

func EnsureString Uses

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 Uses

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 Uses

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 LengthOfValue Uses

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 Uses

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 Uses

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

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

func ToInt Uses

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

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

func ToUint Uses

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

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

func Validate Uses

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 Uses

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 Uses

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 Uses

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.

type DateRule Uses

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

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

func Date Uses

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 Uses

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) Max Uses

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 Uses

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 Uses

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) Validate Uses

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

Validate checks if the given value is a valid date.

type EachRule Uses

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 Uses

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 Uses

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

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

type ErrFieldNotFound Uses

type ErrFieldNotFound int

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

func (ErrFieldNotFound) Error Uses

func (e ErrFieldNotFound) Error() string

Error returns the error string of ErrFieldNotFound.

type ErrFieldPointer Uses

type ErrFieldPointer int

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

func (ErrFieldPointer) Error Uses

func (e ErrFieldPointer) Error() string

Error returns the error string of ErrFieldPointer.

type Errors Uses

type Errors map[string]error

Errors represents the validation errors that are indexed by struct field names, map or slice keys.

func (Errors) Error Uses

func (es Errors) Error() string

Error returns the error string of Errors.

func (Errors) Filter Uses

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 Uses

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

MarshalJSON converts the Errors into a valid JSON.

type FieldRules Uses

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

FieldRules represents a rule set associated with a struct field.

func Field Uses

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 Uses

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 Uses

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 Uses

func (r InRule) Error(message string) InRule

Error sets the error message for the rule.

func (InRule) Validate Uses

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

Validate checks if the given value is valid or not.

type InternalError Uses

type InternalError interface {
    error
    InternalError() error
}

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

func NewInternalError Uses

func NewInternalError(err error) InternalError

NewInternalError wraps a given error into an InternalError.

type LengthRule Uses

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 Uses

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 Uses

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 Uses

func (v LengthRule) Error(message string) LengthRule

Error sets the error message for the rule.

func (LengthRule) Validate Uses

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

Validate checks if the given value is valid or not.

type MatchRule Uses

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 Uses

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 Uses

func (v MatchRule) Error(message string) MatchRule

Error sets the error message for the rule.

func (MatchRule) Validate Uses

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

Validate checks if the given value is valid or not.

type MultipleOfRule Uses

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 Uses

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 Uses

func (r MultipleOfRule) Error(message string) MultipleOfRule

Error sets the error message for the rule.

func (MultipleOfRule) Validate Uses

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

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

type NotInRule Uses

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 Uses

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 Uses

func (r NotInRule) Error(message string) NotInRule

Error sets the error message for the rule.

func (NotInRule) Validate Uses

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

Validate checks if the given value is valid or not.

type Rule Uses

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 Uses

func By(f RuleFunc) Rule

By wraps a RuleFunc into a Rule.

func WithContext Uses

func WithContext(f RuleWithContextFunc) Rule

WithContext wraps a RuleWithContextFunc into a context-aware Rule.

type RuleFunc Uses

type RuleFunc func(value interface{}) error

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

type RuleWithContext Uses

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 Uses

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 Uses

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

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

func NewStringRule Uses

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 (StringRule) Error Uses

func (v StringRule) Error(message string) StringRule

Error sets the error message for the rule.

func (StringRule) Validate Uses

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

Validate checks if the given value is valid or not.

type ThresholdRule Uses

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 Uses

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 Uses

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 Uses

func (r ThresholdRule) Error(message string) ThresholdRule

Error sets the error message for the rule.

func (ThresholdRule) Exclusive Uses

func (r ThresholdRule) Exclusive() ThresholdRule

Exclusive sets the comparison to exclude the boundary value.

func (ThresholdRule) Validate Uses

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

Validate checks if the given value is valid or not.

type Validatable Uses

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 Uses

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.

Directories

PathSynopsis
isPackage is provides a list of commonly used string validation rules.

Package validation imports 12 packages (graph) and is imported by 210 packages. Updated 2019-12-05. Refresh now. Tools for package owners.