Documentation
¶
Overview ¶
Package validation provides configurable and extensible rules for validating data of various types.
Index ¶
- Constants
- Variables
- func EnsureString(value interface{}) (string, error)
- func GetThis(ctx context.Context) any
- func Indirect(value interface{}) (interface{}, bool)
- func IsChanged(original, value any) bool
- func IsEmpty(value interface{}) bool
- func IsValidationError(err error) bool
- func IsVisited(ctx context.Context, ptr uintptr) bool
- func LengthOfValue(value interface{}) (int, error)
- func MarshalRule(r RuleEx) ([]byte, error)
- func MarshalRules(rules []RuleEx) ([]byte, error)
- func RegisterRule(rule RuleEx)
- func RegisterUnmarshaller(t RuleType, unmarshaller Unmarshaller)
- func StringOrBytes(value interface{}) (isString bool, str string, isBytes bool, bs []byte)
- func ToFloat(value interface{}) (float64, error)
- func ToInt(value interface{}) (int64, error)
- func ToUint(value interface{}) (uint64, error)
- func UpdateLevelChildrenNamesByModelTags(err error, model interface{}) error
- func Validate(ctx context.Context, value interface{}, rules ...Rule) error
- func ValidateStruct(ctx context.Context, structPtr interface{}, fields ...*FieldRules) error
- func WithPrivilegeResolver(ctx context.Context, resolver PrivilegeResolver) context.Context
- func WithThis(ctx context.Context, this any) context.Context
- func WithVisitContext(ctx context.Context, value interface{}) context.Context
- type BoolRule
- type Boolean
- type CriteriaRule
- func (r CriteriaRule) Error(message string) CriteriaRule
- func (r CriteriaRule) ErrorObject(err Error) CriteriaRule
- func (r *CriteriaRule) MarshalJSON() ([]byte, error)
- func (r CriteriaRule) RuleType() RuleType
- func (r *CriteriaRule) UnmarshalJSON(data []byte) error
- func (r CriteriaRule) Validate(ctx context.Context, value interface{}) error
- func (r CriteriaRule) When(condition bool) CriteriaRule
- type DateRule
- func (r DateRule) Error(message string) DateRule
- func (r DateRule) ErrorObject(err Error) DateRule
- func (r DateRule) MarshalJSON() ([]byte, error)
- func (r DateRule) Max(max time.Time) DateRule
- func (r DateRule) Min(min time.Time) DateRule
- func (r DateRule) RangeError(message string) DateRule
- func (r DateRule) RangeErrorObject(err Error) DateRule
- func (r DateRule) RuleType() RuleType
- func (r *DateRule) UnmarshalJSON(data []byte) error
- func (r DateRule) Validate(_ context.Context, value interface{}) error
- func (r DateRule) When(condition bool) DateRule
- type Declarations
- type Declarator
- type DependsOnRule
- type EachRule
- type ErrFieldNotFound
- type ErrFieldPointer
- type Error
- type ErrorDictionary
- type ErrorLevel
- func (l *ErrorLevel) AddChildError(key string, err error) bool
- func (l *ErrorLevel) AddError(err error) bool
- func (l *ErrorLevel) Error() string
- func (l *ErrorLevel) Is(target error) bool
- func (l *ErrorLevel) IsEmpty() bool
- func (l *ErrorLevel) MarshalJSON() ([]byte, error)
- func (l *ErrorLevel) Merge(other *ErrorLevel)
- func (l *ErrorLevel) Result() error
- func (l *ErrorLevel) Unwrap() []error
- func (l *ErrorLevel) UpdateChildrenNamesByModelTags(model interface{})
- func (l *ErrorLevel) UpdateChildrenNamesByTypeTags(typ reflect.Type)
- type ErrorList
- type ErrorObject
- func (e ErrorObject) AddParam(name string, value interface{}) Error
- func (e ErrorObject) Cause() error
- func (e ErrorObject) Code() string
- func (e ErrorObject) Error() string
- func (e ErrorObject) Is(target error) bool
- func (e ErrorObject) Message() string
- func (e ErrorObject) Params() map[string]interface{}
- func (e ErrorObject) SetCause(cause error) Error
- func (e ErrorObject) SetCode(code string) Error
- func (e ErrorObject) SetMessage(message string) Error
- func (e ErrorObject) SetParams(params map[string]interface{}) Error
- func (e ErrorObject) Unwrap() []error
- type Errors
- type FieldRules
- type Float
- type InRule
- func (r InRule) Error(message string) InRule
- func (r InRule) ErrorObject(err Error) InRule
- func (r *InRule) MarshalJSON() ([]byte, error)
- func (r InRule) RuleType() RuleType
- func (r *InRule) UnmarshalJSON(data []byte) error
- func (r InRule) Validate(_ context.Context, value interface{}) error
- func (r InRule) When(condition bool) InRule
- type Integer
- type InternalError
- type JsonRule
- type JsonSchema
- type KeyRules
- type LengthRule
- func (r LengthRule) Error(message string) LengthRule
- func (r LengthRule) ErrorObject(err Error) LengthRule
- func (r *LengthRule) MarshalJSON() ([]byte, error)
- func (r LengthRule) RuleType() RuleType
- func (r *LengthRule) UnmarshalJSON(data []byte) error
- func (r LengthRule) Validate(_ context.Context, value interface{}) error
- func (r LengthRule) When(condition bool) LengthRule
- type MatchRule
- func (r MatchRule) Error(message string) MatchRule
- func (r MatchRule) ErrorObject(err Error) MatchRule
- func (r *MatchRule) MarshalJSON() ([]byte, error)
- func (r MatchRule) RuleType() RuleType
- func (r *MatchRule) UnmarshalJSON(data []byte) error
- func (r MatchRule) Validate(_ context.Context, value interface{}) error
- func (r MatchRule) When(condition bool) MatchRule
- type MultipleOfRule
- func (r MultipleOfRule) Error(message string) MultipleOfRule
- func (r MultipleOfRule) ErrorObject(err Error) MultipleOfRule
- func (r MultipleOfRule) MarshalJSON() ([]byte, error)
- func (r MultipleOfRule) RuleType() RuleType
- func (r *MultipleOfRule) UnmarshalJSON(data []byte) error
- func (r MultipleOfRule) Validate(_ context.Context, value interface{}) error
- func (r MultipleOfRule) When(condition bool) MultipleOfRule
- type NotInRule
- func (r NotInRule) Error(message string) NotInRule
- func (r NotInRule) ErrorObject(err Error) NotInRule
- func (r NotInRule) MarshalJSON() ([]byte, error)
- func (r NotInRule) RuleType() RuleType
- func (r *NotInRule) UnmarshalJSON(data []byte) error
- func (r NotInRule) Validate(_ context.Context, value interface{}) error
- func (r NotInRule) When(condition bool) NotInRule
- type Primitive
- type PrivilegeResolver
- type PrivilegeRule
- type RequiredRule
- func (r RequiredRule) Error(message string) RequiredRule
- func (r RequiredRule) ErrorObject(err Error) RequiredRule
- func (r *RequiredRule) MarshalJSON() ([]byte, error)
- func (r RequiredRule) RuleType() RuleType
- func (r *RequiredRule) UnmarshalJSON(data []byte) error
- func (r RequiredRule) Validate(_ context.Context, value interface{}) error
- func (r RequiredRule) When(condition bool) RequiredRule
- type Rule
- type RuleEx
- type RuleExs
- type RuleFunc
- type RuleType
- type String
- type StringRule
- func (r StringRule) Error(message string) StringRule
- func (r StringRule) ErrorObject(err Error) StringRule
- func (r StringRule) MarshalJSON() ([]byte, error)
- func (r StringRule) RuleType() RuleType
- func (r StringRule) UnmarshalJSON(data []byte) error
- func (r StringRule) Validate(_ context.Context, value interface{}) error
- func (r StringRule) When(condition bool) StringRule
- type ThresholdRule
- func (r ThresholdRule) Error(message string) ThresholdRule
- func (r ThresholdRule) ErrorObject(err Error) ThresholdRule
- func (r ThresholdRule) Exclusive() ThresholdRule
- func (r ThresholdRule) MarshalJSON() ([]byte, error)
- func (r ThresholdRule) RuleType() RuleType
- func (r *ThresholdRule) UnmarshalJSON(data []byte) error
- func (r ThresholdRule) Validate(_ context.Context, value interface{}) error
- func (r ThresholdRule) When(condition bool) ThresholdRule
- type TypeRule
- func (r TypeRule) Error(message string) TypeRule
- func (r TypeRule) ErrorObject(err Error) TypeRule
- func (r *TypeRule) MarshalJSON() ([]byte, error)
- func (r TypeRule) RuleType() RuleType
- func (r *TypeRule) UnmarshalJSON(data []byte) error
- func (r TypeRule) Validate(_ context.Context, value interface{}) error
- func (r TypeRule) When(condition bool) TypeRule
- type UnchangeableRule
- type UniqueListRule
- type UniqueRule
- type Unmarshaller
- type Validatable
- type ValidatorDTO
- type Valuable
- type WhenRule
Constants ¶
const ( RuleTypeRequired = "required" RuleTypeNirOrNotEmpty = "nil_or_not_empty" )
const (
MatchRuleType = "match"
)
const (
NotInRuleType = "not_in"
)
const (
RuleTypeDate = "date"
)
const (
RuleTypeDependsOn = "depends_on"
)
const (
RuleTypeMultipleOf = "multiple_of"
)
const (
RuleTypeNotNil = "not_nil"
)
Variables ¶
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") )
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") )
var ( // ErrJsonInvalid is the error that returns in case of an invalid json. ErrJsonInvalid = NewError("validation_json_invalid", "must be a valid json") // ErrJsonInvalidMarshall is the error that returns in case of an error during marshalling. ErrJsonInvalidMarshall = NewError("validation_json_invalid_marshall", "error marshalling json") // ErrJsonInvalidUnmarshall is the error that returns in case of an error during unmarshalling. ErrJsonInvalidUnmarshall = NewError("validation_json_invalid_unmarshall", "error unmarshalling json") )
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") )
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") )
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}}") )
var ( ErrValidationIntegerUnmarshal = NewError("validation_integer_unmarshal", "failed to unmarshal integer value") ErrValidationFloatUnmarshal = NewError("validation_float_unmarshal", "failed to unmarshal float value") ErrValidationStringUnmarshal = NewError("validation_string_unmarshal", "failed to unmarshal string value") ErrValidationBooleanUnmarshal = NewError("validation_boolean_unmarshal", "failed to unmarshal boolean value") )
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") )
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 */} )
var Empty = absentRule{ // contains filtered or unexported fields }
Empty checks if a not nil value is empty.
var ErrCELCompilation = NewError("validation_cel_compilation_error", "CEL compilation error")
ErrCELCompilation is the error that returns when CEL compilation fails.
var ErrCELEnvironment = NewError("validation_cel_error", "can't create CEL environment")
ErrCELEnvironment is the error that returns when CEL environment cannot be created.
var ErrCELEvaluation = NewError("validation_cel_evaluation_error", "error evaluating CEL expression")
ErrCELEvaluation is the error that returns when CEL evaluation fails.
var ErrCELProgram = NewError("validation_cel_program_error", "error creating CEL program")
ErrCELProgram is the error that returns when CEL program cannot be created.
var ErrCriteriaIsNotMatch = NewError("validation_value_do_not_match_criteria", "value don't match criteria")
ErrCriteriaIsNotMatch is the error that returns in case of an invalid value for "in" rule.
var ErrFalseInvalid = NewError("validation_false_invalid", "must be in a false value")
ErrFalseInvalid is the error that returns in case of changed value.
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.
var ErrInvalidKey = NewError("validation_invalid_key", "key is not valid")
ErrInvalidKey is the error returned when a key in a map is not valid according to the specified rules.
var ErrMatchInvalid = NewError("validation_match_invalid", "must be in a valid format")
ErrMatchInvalid is the error that returns in case of invalid format.
var ( // ErrMissingPrivilege is the error returned when a user does not have the required privilege. ErrMissingPrivilege = NewError("validation_missing_privilege", "user does not have the required privilege") )
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.
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.
var ErrNotNilRequired = NewError("validation_not_nil_required", "is required")
ErrNotNilRequired is the error that returns when a value is Nil.
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 ErrTrueInvalid = NewError("validation_true_invalid", "must be in a true value")
ErrTrueInvalid is the error that returns in case of changed value.
var ErrTypeInvalid = NewError("validation_type_invalid", "must be a valid type")
ErrTypeInvalid is the error that returns in case of an invalid type for "type" rule.
var ErrUnchangeableInvalid = NewError("validation_unchangeable_invalid", "must be in a unchangeable value")
ErrUnchangeableInvalid is the error that returns in case of changed value.
var ErrUniqueDuplicate = NewError("validation_unique_duplication", "must be an unique value")
ErrUniqueDuplicate is the error that returns in case of an duplication value for "unique" rule.
var ErrUniqueListDuplicate = NewError("validation_unique_list_duplication", "must have unique values")
ErrUniqueListDuplicate is the error that returns in case of an duplication value for "unique" rule.
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
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 PrimitiveErrors = map[string]Error{ new(Integer).GetName(): ErrValidationIntegerUnmarshal, new(Float).GetName(): ErrValidationFloatUnmarshal, new(String).GetName(): ErrValidationStringUnmarshal, new(Boolean).GetName(): ErrValidationBooleanUnmarshal, }
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 ¶
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. 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 IsValidationError ¶
func LengthOfValue ¶
LengthOfValue returns the length of a value that is a string, slice, map, or array. An error is returned for all other types.
func MarshalRule ¶
func MarshalRules ¶
func RegisterRule ¶
func RegisterRule(rule RuleEx)
func RegisterUnmarshaller ¶
func RegisterUnmarshaller(t RuleType, unmarshaller Unmarshaller)
func StringOrBytes ¶
StringOrBytes typecasts a value into a string or byte slice. Boolean flags are returned to indicate if the typecasting succeeds or not.
func ToFloat ¶
ToFloat converts the given value to a float64. An error is returned for all incompatible types.
func ToInt ¶
ToInt converts the given value to an int64. An error is returned for all incompatible types.
func ToUint ¶
ToUint converts the given value to an uint64. An error is returned for all incompatible types.
func UpdateLevelChildrenNamesByModelTags ¶
UpdateLevelChildrenNamesByModelTags recurrence updates the names of the children in the error level by using the provided model's tags.
func Validate ¶
Validate validates the given value with the given context and returns the validation error, if any.
Validate performs validation using the following steps:
- 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.
- If the value being validated implements `ValidatableWithContext`, call the value's `ValidateWithContext()` and return with the validation result.
- If the value being validated implements `Validatable`, call the value's `Validate()` and return with the validation result.
- 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(ctx context.Context, 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 WithPrivilegeResolver ¶
func WithPrivilegeResolver(ctx context.Context, resolver PrivilegeResolver) context.Context
WithPrivilegeResolver adds a PrivilegeResolver to the context.
Types ¶
type BoolRule ¶
type BoolRule struct {
// contains filtered or unexported fields
}
BoolRule is a validation rule that checks if a value bool.
func False ¶
False returns a validation rule that checks if a value false. 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 True ¶
True returns a validation rule that checks if a value true. 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 (BoolRule) ErrorObject ¶
ErrorObject sets the error struct for the rule.
type CriteriaRule ¶
type CriteriaRule struct {
// contains filtered or unexported fields
}
CriteriaRule is a validation rule that validates if a value match given value.
func Criteria ¶
func Criteria(expr string) CriteriaRule
Criteria returns a validation rule that checks if a value is match given value
func (CriteriaRule) Error ¶
func (r CriteriaRule) Error(message string) CriteriaRule
Error sets the error message for the rule.
func (CriteriaRule) ErrorObject ¶
func (r CriteriaRule) ErrorObject(err Error) CriteriaRule
ErrorObject sets the error struct for the rule.
func (*CriteriaRule) MarshalJSON ¶
func (r *CriteriaRule) MarshalJSON() ([]byte, error)
func (CriteriaRule) RuleType ¶
func (r CriteriaRule) RuleType() RuleType
func (*CriteriaRule) UnmarshalJSON ¶
func (r *CriteriaRule) UnmarshalJSON(data []byte) error
func (CriteriaRule) Validate ¶
func (r CriteriaRule) Validate(ctx context.Context, value interface{}) error
Validate checks if the given value is valid or not.
func (CriteriaRule) When ¶
func (r CriteriaRule) When(condition bool) CriteriaRule
When sets the condition that determines if the validation should be performed.
type DateRule ¶
type DateRule struct {
// contains filtered or unexported fields
}
DateRule is a validation rule that validates date/time string values.
func Date ¶
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 ¶
Error sets the error message that is used when the value being validated is not a valid date.
func (DateRule) ErrorObject ¶
ErrorObject sets the error struct that is used when the value being validated is not a valid date..
func (DateRule) MarshalJSON ¶
func (DateRule) Max ¶
Max sets the maximum date range. A zero value means skipping the maximum range validation.
func (DateRule) Min ¶
Min sets the minimum date range. A zero value means skipping the minimum range validation.
func (DateRule) RangeError ¶
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 ¶
RangeErrorObject sets the error struct that is used when the value being validated is out of the specified Min/Max date range.
func (*DateRule) UnmarshalJSON ¶
UnmarshalJSON unmarshals the JSON data into the DateRule struct.
type Declarations ¶
type Declarator ¶
type Declarator interface {
DeclareValidationFields(declarations Declarations)
}
type DependsOnRule ¶
type DependsOnRule struct {
// contains filtered or unexported fields
}
DependsOnRule is a validation rule that executes the given list of rules dependsOn the condition is true.
func DependsOn ¶
func DependsOn(condition string, rules ...RuleEx) DependsOnRule
DependsOn returns a validation rule that executes the given list of rules dependsOn the condition is true.
func (DependsOnRule) Else ¶
func (r DependsOnRule) Else(rules ...RuleEx) DependsOnRule
Else returns a validation rule that executes the given list of rules dependsOn the condition is false.
func (*DependsOnRule) MarshalJSON ¶
func (r *DependsOnRule) MarshalJSON() ([]byte, error)
func (DependsOnRule) RuleType ¶
func (r DependsOnRule) RuleType() RuleType
func (*DependsOnRule) UnmarshalJSON ¶
func (r *DependsOnRule) UnmarshalJSON(data []byte) error
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 ¶
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.
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
Cause() error
SetCode(string) Error
SetMessage(string) Error
SetCause(error) Error
Params() map[string]interface{}
SetParams(map[string]interface{}) Error
AddParam(name string, value interface{}) Error
}
Error interface represents an validation error
type ErrorDictionary ¶
func (ErrorDictionary) Add ¶
func (d ErrorDictionary) Add(key string, err error)
func (ErrorDictionary) IsEmpty ¶
func (d ErrorDictionary) IsEmpty() bool
func (ErrorDictionary) ToErrors ¶
func (d ErrorDictionary) ToErrors() Errors
type ErrorLevel ¶
func EnsureLevel ¶
func EnsureLevel(err error) *ErrorLevel
EnsureLevel converts the given error into an ErrorLevel.
func NewErrorLevel ¶
func NewErrorLevel() *ErrorLevel
func (*ErrorLevel) AddChildError ¶
func (l *ErrorLevel) AddChildError(key string, err error) bool
func (*ErrorLevel) AddError ¶
func (l *ErrorLevel) AddError(err error) bool
func (*ErrorLevel) Error ¶
func (l *ErrorLevel) Error() string
func (*ErrorLevel) Is ¶
func (l *ErrorLevel) Is(target error) bool
func (*ErrorLevel) IsEmpty ¶
func (l *ErrorLevel) IsEmpty() bool
func (*ErrorLevel) MarshalJSON ¶
func (l *ErrorLevel) MarshalJSON() ([]byte, error)
func (*ErrorLevel) Merge ¶
func (l *ErrorLevel) Merge(other *ErrorLevel)
func (*ErrorLevel) Result ¶
func (l *ErrorLevel) Result() error
func (*ErrorLevel) Unwrap ¶
func (l *ErrorLevel) Unwrap() []error
func (*ErrorLevel) UpdateChildrenNamesByModelTags ¶
func (l *ErrorLevel) UpdateChildrenNamesByModelTags(model interface{})
func (*ErrorLevel) UpdateChildrenNamesByTypeTags ¶
func (l *ErrorLevel) UpdateChildrenNamesByTypeTags(typ reflect.Type)
type ErrorList ¶
type ErrorList []error
ErrorList represents a list of errors.
func (ErrorList) Is ¶
Is implements the errors.Is interface to check if the error matches a target error.
func (ErrorList) MarshalJSON ¶
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) Cause ¶
func (e ErrorObject) Cause() error
Cause returns the cause of the error, if any.
func (ErrorObject) Is ¶
func (e ErrorObject) Is(target error) bool
Is implements the errors.Is interface to check if the error matches a target error.
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) SetCause ¶
func (e ErrorObject) SetCause(cause error) Error
SetCause sets the cause of the error.
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.
func (ErrorObject) Unwrap ¶
func (e ErrorObject) Unwrap() []error
type Errors ¶
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) Filter ¶
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) Is ¶
Is implements the errors.Is interface to check if the error matches a target error.
func (Errors) MarshalJSON ¶
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.
func Integrity ¶
func Integrity(rules ...Rule) *FieldRules
Integrity creates a FieldRules that is used to validate the integrity of a struct whole.
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) ErrorObject ¶
ErrorObject sets the error struct for the rule.
func (*InRule) MarshalJSON ¶
func (*InRule) UnmarshalJSON ¶
type InternalError ¶
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 JsonRule ¶
type JsonRule struct {
// contains filtered or unexported fields
}
JsonRule is a validation rule that valijsons json/time string values.
func Json ¶
func Json(schema JsonSchema) JsonRule
func (JsonRule) Error ¶
Error sets the error message that is used when the value being valijsond is not a valid json.
func (JsonRule) ErrorObject ¶
ErrorObject sets the error struct that is used when the value being valijsond is not a valid json..
type JsonSchema ¶
JsonSchema is an interface that defines a method for validating JSON values. It may be implemented by any type that can validate JSON data. For example: github.com/santhosh-tekuri/jsonschema/v5
type KeyRules ¶
type KeyRules struct {
// contains filtered or unexported fields
}
KeyRules represents a rule set associated with a map key.
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) MarshalJSON ¶
func (r *LengthRule) MarshalJSON() ([]byte, error)
func (LengthRule) RuleType ¶
func (r LengthRule) RuleType() RuleType
func (*LengthRule) UnmarshalJSON ¶
func (r *LengthRule) UnmarshalJSON(data []byte) error
func (LengthRule) Validate ¶
func (r LengthRule) Validate(_ context.Context, value interface{}) error
Validate checks if the given value is valid or not.
func (LengthRule) When ¶
func (r LengthRule) When(condition bool) LengthRule
When sets the condition that determines if the validation should be performed.
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 ¶
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) ErrorObject ¶
ErrorObject sets the error struct for the rule.
func (*MatchRule) MarshalJSON ¶
func (*MatchRule) UnmarshalJSON ¶
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) MarshalJSON ¶
func (r MultipleOfRule) MarshalJSON() ([]byte, error)
func (MultipleOfRule) RuleType ¶
func (r MultipleOfRule) RuleType() RuleType
func (*MultipleOfRule) UnmarshalJSON ¶
func (r *MultipleOfRule) UnmarshalJSON(data []byte) error
func (MultipleOfRule) Validate ¶
func (r MultipleOfRule) Validate(_ context.Context, value interface{}) error
Validate checks if the value is a multiple of the "base" value.
func (MultipleOfRule) When ¶
func (r MultipleOfRule) When(condition bool) MultipleOfRule
When sets the condition that determines if the validation should be performed.
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) ErrorObject ¶
ErrorObject sets the error struct for the rule.
func (NotInRule) MarshalJSON ¶
func (*NotInRule) UnmarshalJSON ¶
type PrivilegeResolver ¶
type PrivilegeResolver interface {
HasPrivilege(ctx context.Context, resource, action string) (bool, error)
}
func GetPrivilegeResolver ¶
func GetPrivilegeResolver(ctx context.Context) PrivilegeResolver
GetPrivilegeResolver retrieves the PrivilegeResolver from the context.
type PrivilegeRule ¶
type PrivilegeRule struct {
// contains filtered or unexported fields
}
PrivilegeRule checks if the user has the required privilege.
func Privilege ¶
func Privilege( resource string, action string, ) PrivilegeRule
Privilege is a constructor for a privilege validation rule.
func (PrivilegeRule) Error ¶
func (that PrivilegeRule) Error(message string) PrivilegeRule
Error sets the error message for the rule.
func (PrivilegeRule) ErrorObject ¶
func (that PrivilegeRule) ErrorObject(err Error) PrivilegeRule
ErrorObject sets the error struct for the rule.
func (PrivilegeRule) Validate ¶
func (that PrivilegeRule) Validate(ctx context.Context, value interface{}) error
func (PrivilegeRule) When ¶
func (that PrivilegeRule) When(condition bool) PrivilegeRule
When sets the condition that determines if the validation should be performed.
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) MarshalJSON ¶
func (r *RequiredRule) MarshalJSON() ([]byte, error)
func (RequiredRule) RuleType ¶
func (r RequiredRule) RuleType() RuleType
func (*RequiredRule) UnmarshalJSON ¶
func (r *RequiredRule) UnmarshalJSON(data []byte) error
func (RequiredRule) Validate ¶
func (r RequiredRule) Validate(_ context.Context, 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(ctx context.Context, value interface{}) error
}
Rule represents a validation rule.
type RuleEx ¶
RuleEx is an extended Rule interface that includes a Type method to return the type of the rule. You must use it for serialization purposes.
func UnmarshalRule ¶
func UnmarshalRules ¶
type RuleFunc ¶
RuleFunc represents a validator function. You may wrap it as a Rule by calling By().
type RuleType ¶
type RuleType string
const (
RuleTypeCriteria RuleType = "criteria"
)
const (
RuleTypeIn RuleType = "in"
)
const (
RuleTypeLength RuleType = "length"
)
const (
RuleTypeType RuleType = "type"
)
const (
ThresholdRuleType RuleType = "threshold"
)
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(t RuleType, 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(t RuleType, 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) MarshalJSON ¶
func (r StringRule) MarshalJSON() ([]byte, error)
func (StringRule) RuleType ¶
func (r StringRule) RuleType() RuleType
func (StringRule) UnmarshalJSON ¶
func (r StringRule) UnmarshalJSON(data []byte) error
func (StringRule) Validate ¶
func (r StringRule) Validate(_ context.Context, value interface{}) error
Validate checks if the given value is valid or not.
func (StringRule) When ¶
func (r StringRule) When(condition bool) StringRule
When sets the condition that determines if the validation should be performed.
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) MarshalJSON ¶
func (r ThresholdRule) MarshalJSON() ([]byte, error)
func (ThresholdRule) RuleType ¶
func (r ThresholdRule) RuleType() RuleType
func (*ThresholdRule) UnmarshalJSON ¶
func (r *ThresholdRule) UnmarshalJSON(data []byte) error
func (ThresholdRule) Validate ¶
func (r ThresholdRule) Validate(_ context.Context, value interface{}) error
Validate checks if the given value is valid or not.
func (ThresholdRule) When ¶
func (r ThresholdRule) When(condition bool) ThresholdRule
When sets the condition that determines if the validation should be performed.
type TypeRule ¶
type TypeRule struct {
// contains filtered or unexported fields
}
TypeRule is a validation rule that validates if a value has one of given list names of types.
func Type ¶
Type returns a validation rule that checks if a value is match required type. 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 (TypeRule) ErrorObject ¶
ErrorObject sets the error struct for the rule.
func (*TypeRule) MarshalJSON ¶
func (*TypeRule) UnmarshalJSON ¶
type UnchangeableRule ¶
type UnchangeableRule struct {
// contains filtered or unexported fields
}
UnchangeableRule is a validation rule that checks if a value unchangeable.
func Unchangeable ¶
func Unchangeable(original any) UnchangeableRule
Unchangeable returns a validation rule that checks if a value unchangeable. 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 (UnchangeableRule) Error ¶
func (r UnchangeableRule) Error(message string) UnchangeableRule
Error sets the error message for the rule.
func (UnchangeableRule) ErrorObject ¶
func (r UnchangeableRule) ErrorObject(err Error) UnchangeableRule
ErrorObject sets the error struct for the rule.
func (UnchangeableRule) Validate ¶
func (r UnchangeableRule) Validate(_ context.Context, value interface{}) error
Validate checks if the given value is valid or not.
func (UnchangeableRule) When ¶
func (r UnchangeableRule) When(condition bool) UnchangeableRule
When sets the condition that determines if the validation should be performed.
type UniqueListRule ¶
type UniqueListRule struct {
// contains filtered or unexported fields
}
UniqueListRule is a validation rule that validates if a value can be unique in the given list of values.
func UniqueList ¶
func UniqueList() UniqueListRule
UniqueList returns a validation rule that checks if a value can be unique 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 (UniqueListRule) Error ¶
func (r UniqueListRule) Error(message string) UniqueListRule
Error sets the error message for the rule.
func (UniqueListRule) ErrorObject ¶
func (r UniqueListRule) ErrorObject(err Error) UniqueListRule
ErrorObject sets the error struct for the rule.
func (UniqueListRule) Validate ¶
func (r UniqueListRule) Validate(_ context.Context, value interface{}) error
Validate checks if the given value is valid or not.
func (UniqueListRule) When ¶
func (r UniqueListRule) When(condition bool) UniqueListRule
When sets the condition that determines if the validation should be performed.
type UniqueRule ¶
type UniqueRule struct {
// contains filtered or unexported fields
}
UniqueRule is a validation rule that validates if a value can be unique in the given list of values.
func Unique ¶
func Unique(values ...interface{}) UniqueRule
Unique returns a validation rule that checks if a value can be unique 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 (UniqueRule) Error ¶
func (r UniqueRule) Error(message string) UniqueRule
Error sets the error message for the rule.
func (UniqueRule) ErrorObject ¶
func (r UniqueRule) ErrorObject(err Error) UniqueRule
ErrorObject sets the error struct for the rule.
func (UniqueRule) Validate ¶
func (r UniqueRule) Validate(_ context.Context, value interface{}) error
Validate checks if the given value is valid or not.
func (UniqueRule) When ¶
func (r UniqueRule) When(condition bool) UniqueRule
When sets the condition that determines if the validation should be performed.
type Unmarshaller ¶
type Validatable ¶
type Validatable interface {
// Validate validates the data and returns an error if validation fails.
Validate(ctx context.Context) error
}
Validatable is the interface indicating the type implementing it supports data validation.
type ValidatorDTO ¶
type ValidatorDTO struct {
Type string `json:"type"`
Data json.RawMessage `json:"data"`
}
type Valuable ¶
type Valuable interface {
// GetValue returns the value of the object.
GetValue() interface{}
}
Valuable is the interface indicating the type implementing it can return its value.
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 ¶
When returns a validation rule that executes the given list of rules when the condition is true.
