Documentation
¶
Overview ¶
Package valix - Go package for validating requests
Check requests in the form of *http.Request, `map[string]interface{}` or `[]interface{}`
Validators can be created from existing structs, for example:
type AddPersonRequest struct {
Name string `json:"name" v8n:"notNull,mandatory,&StringNoControlCharacters{},&StringLength{Minimum: 1, Maximum: 255}"`
Age int `json:"age" v8n:"type:Integer,notNull,mandatory,&PositiveOrZero{}"`
}
var AddPersonRequestValidator = valix.MustCompileValidatorFor(AddPersonRequest{}, nil)
Or validators can be expressed effectively in code, for example:
var personValidator = &valix.Validator{
IgnoreUnknownProperties: false,
Properties: valix.Properties{
"name": {
Type: valix.Type.JsonString,
NotNull: true,
Mandatory: true,
Constraints: valix.Constraints{
&valix.StringLength{Minimum: 1, Maximum: 255},
},
},
"age": {
Type: valix.Type.Int,
NotNull: true,
Mandatory: true,
Constraints: valix.Constraints{
&valix.PositiveOrZero{},
},
},
},
}
Validators can re-use common property validators, for example re-using the `personValidator` above:
var addPersonToGroupValidator = &valix.Validator{
IgnoreUnknownProperties: false,
Properties: valix.Properties{
"person": {
Type: valix.Type.JsonObject,
ObjectValidator: personValidator,
},
"group": {
Type: valix.Type.JsonString,
NotNull: true,
Mandatory: true,
Constraints: valix.Constraints{
&valix.StringLength{Minimum: 1, Maximum: 255},
},
},
},
}
Index ¶
- Constants
- Variables
- func ClearCustomTagTokens()
- func ClearCustomTags()
- func ClearTagTokenAliases()
- func ConstraintsRegistryHas(name string) bool
- func ConstraintsRegistryReset()
- func PropertiesRepoClear()
- func PropertiesRepoPanics(panics bool)
- func ReRegisterConstraint(constraint Constraint)
- func ReRegisterConstraints(constraints ...Constraint)
- func ReRegisterNamedConstraint(name string, constraint Constraint)
- func ReRegisterNamedConstraints(constraints map[string]Constraint)
- func RegisterConstraint(constraint Constraint)
- func RegisterConstraints(constraints ...Constraint)
- func RegisterCustomTag(tag string, handler TagHandler)
- func RegisterCustomTagToken(token string, handler CustomTagTokenHandler)
- func RegisterNamedConstraint(name string, constraint Constraint)
- func RegisterNamedConstraints(constraints map[string]Constraint)
- func RegisterPreset(token string, preset Preset, asConstraint bool)
- func RegisterPresetPattern(token string, rx *regexp.Regexp, message string, postCheck PostPatternChecker, ...)
- func RegisterProperties(properties Properties)
- func RegisterTagTokenAlias(alias string, val string)
- func RegisterTagTokenAliases(aliases TagAliases)
- func SortViolationsByPathAndProperty(violations []*Violation)
- type ArrayConditionalConstraint
- func (c *ArrayConditionalConstraint) Check(v interface{}, vcx *ValidatorContext) (bool, string)
- func (c *ArrayConditionalConstraint) GetMessage(tcx I18nContext) string
- func (c *ArrayConditionalConstraint) MarshalJSON() ([]byte, error)
- func (c *ArrayConditionalConstraint) UnmarshalJSON(data []byte) error
- type ArrayDistinctProperty
- type ArrayOf
- type ArrayUnique
- type BooleanOperator
- type Check
- type Conditional
- type ConditionalConstraint
- type ConditionalVariant
- type ConditionalVariants
- type Conditions
- type Constraint
- type ConstraintSet
- type Constraints
- type CustomConstraint
- type CustomTagTokenHandler
- type DatetimeDayOfWeek
- type DatetimeFuture
- type DatetimeFutureOrPresent
- type DatetimeGreaterThan
- type DatetimeGreaterThanOrEqual
- type DatetimeGreaterThanOrEqualOther
- type DatetimeGreaterThanOther
- type DatetimeLessThan
- type DatetimeLessThanOrEqual
- type DatetimeLessThanOrEqualOther
- type DatetimeLessThanOther
- type DatetimePast
- type DatetimePastOrPresent
- type DatetimeRange
- type DatetimeTimeOfDayRange
- type DatetimeTolerance
- type DatetimeToleranceToNow
- type DatetimeToleranceToOther
- type DatetimeYearsOld
- type DecoderProvider
- type Duration
- type EqualsOther
- type FailWhen
- type FailWith
- type FailingConstraint
- type GreaterThan
- type GreaterThanOrEqual
- type GreaterThanOrEqualOther
- type GreaterThanOther
- type I18n
- type I18nContext
- type IsNotNull
- type IsNull
- type JsonType
- type Length
- type LengthExact
- type LessThan
- type LessThanOrEqual
- type LessThanOrEqualOther
- type LessThanOther
- type Maximum
- type MaximumInt
- type Minimum
- type MinimumInt
- type MultipleOf
- type Negative
- type NegativeOrZero
- type NetIsCIDR
- type NetIsHostname
- type NetIsIP
- type NetIsMac
- type NetIsTCP
- type NetIsTld
- type NetIsUDP
- type NetIsURI
- type NetIsURL
- type NotEmpty
- type NotEqualsOther
- type OasInfo
- type Option
- type Other
- type OtherGrouping
- func (g *OtherGrouping) ANDed() *OtherGrouping
- func (g *OtherGrouping) AddAndGroup(of *OthersExpr) *OtherGrouping
- func (g *OtherGrouping) AddAndNotGroup(of *OthersExpr) *OtherGrouping
- func (g *OtherGrouping) AddAndNotProperty(name string) *OtherGrouping
- func (g *OtherGrouping) AddAndProperty(name string) *OtherGrouping
- func (g *OtherGrouping) AddGroup(of *OthersExpr) *OtherGrouping
- func (g *OtherGrouping) AddNotGroup(of *OthersExpr) *OtherGrouping
- func (g *OtherGrouping) AddNotProperty(name string) *OtherGrouping
- func (g *OtherGrouping) AddOrGroup(of *OthersExpr) *OtherGrouping
- func (g *OtherGrouping) AddOrNotGroup(of *OthersExpr) *OtherGrouping
- func (g *OtherGrouping) AddOrNotProperty(name string) *OtherGrouping
- func (g *OtherGrouping) AddOrProperty(name string) *OtherGrouping
- func (g *OtherGrouping) AddProperty(name string) *OtherGrouping
- func (g *OtherGrouping) AddXorGroup(of *OthersExpr) *OtherGrouping
- func (g *OtherGrouping) AddXorNotGroup(of *OthersExpr) *OtherGrouping
- func (g *OtherGrouping) AddXorNotProperty(name string) *OtherGrouping
- func (g *OtherGrouping) AddXorProperty(name string) *OtherGrouping
- func (g *OtherGrouping) Evaluate(currentObj map[string]interface{}, ancestryValues []interface{}, ...) bool
- func (g *OtherGrouping) GetOperator() BooleanOperator
- func (g *OtherGrouping) NOTed() *OtherGrouping
- func (g *OtherGrouping) ORed() *OtherGrouping
- func (g *OtherGrouping) String() string
- func (g *OtherGrouping) XORed() *OtherGrouping
- type OtherProperty
- func (p *OtherProperty) ANDed() *OtherProperty
- func (p *OtherProperty) Evaluate(currentObj map[string]interface{}, ancestryValues []interface{}, ...) bool
- func (p *OtherProperty) GetOperator() BooleanOperator
- func (p *OtherProperty) NOTed() *OtherProperty
- func (p *OtherProperty) ORed() *OtherProperty
- func (p *OtherProperty) String() string
- func (p *OtherProperty) XORed() *OtherProperty
- type OthersExpr
- func (o *OthersExpr) AddAndGroup(of *OthersExpr) *OthersExpr
- func (o *OthersExpr) AddAndNotGroup(of *OthersExpr) *OthersExpr
- func (o *OthersExpr) AddAndNotProperty(name string) *OthersExpr
- func (o *OthersExpr) AddAndProperty(name string) *OthersExpr
- func (o *OthersExpr) AddGroup(of *OthersExpr) *OthersExpr
- func (o *OthersExpr) AddNotGroup(of *OthersExpr) *OthersExpr
- func (o *OthersExpr) AddNotProperty(name string) *OthersExpr
- func (o *OthersExpr) AddOrGroup(of *OthersExpr) *OthersExpr
- func (o *OthersExpr) AddOrNotGroup(of *OthersExpr) *OthersExpr
- func (o *OthersExpr) AddOrNotProperty(name string) *OthersExpr
- func (o *OthersExpr) AddOrProperty(name string) *OthersExpr
- func (o *OthersExpr) AddProperty(name string) *OthersExpr
- func (o *OthersExpr) AddXorGroup(of *OthersExpr) *OthersExpr
- func (o *OthersExpr) AddXorNotGroup(of *OthersExpr) *OthersExpr
- func (o *OthersExpr) AddXorNotProperty(name string) *OthersExpr
- func (o *OthersExpr) AddXorProperty(name string) *OthersExpr
- func (src OthersExpr) Clone() OthersExpr
- func (o *OthersExpr) Evaluate(currentObj map[string]interface{}, ancestryValues []interface{}, ...) bool
- func (o *OthersExpr) GetOperator() BooleanOperator
- func (o *OthersExpr) MarshalJSON() ([]byte, error)
- func (o *OthersExpr) String() string
- func (o *OthersExpr) UnmarshalJSON(data []byte) error
- type Positive
- type PositiveOrZero
- type PostPatternChecker
- type Preset
- type Properties
- type PropertyNameProvider
- type PropertyValidator
- func (pv *PropertyValidator) AddConstraints(c ...Constraint) *PropertyValidator
- func (pv *PropertyValidator) AddMandatoryWhens(c ...string) *PropertyValidator
- func (pv *PropertyValidator) AddUnwantedConditions(c ...string) *PropertyValidator
- func (pv *PropertyValidator) AddWhenConditions(c ...string) *PropertyValidator
- func (pv *PropertyValidator) Clone() *PropertyValidator
- func (pv *PropertyValidator) MarshalJSON() ([]byte, error)
- func (pv *PropertyValidator) SetMandatory() *PropertyValidator
- func (pv *PropertyValidator) SetNotNullable() *PropertyValidator
- func (pv *PropertyValidator) SetNullable() *PropertyValidator
- func (pv *PropertyValidator) SetObjectValidator(v *Validator) *PropertyValidator
- func (pv *PropertyValidator) SetOptional() *PropertyValidator
- func (pv *PropertyValidator) SetOrder(order int) *PropertyValidator
- func (pv *PropertyValidator) SetRequired() *PropertyValidator
- func (pv *PropertyValidator) SetRequiredWith(expr OthersExpr) *PropertyValidator
- func (pv *PropertyValidator) SetRequiredWithMessage(msg string) *PropertyValidator
- func (pv *PropertyValidator) SetType(t JsonType) *PropertyValidator
- func (pv *PropertyValidator) SetUnwantedWith(expr OthersExpr) *PropertyValidator
- func (pv *PropertyValidator) SetUnwantedWithMessage(msg string) *PropertyValidator
- func (pv *PropertyValidator) ToV8nTagString(options *V8nTagStringOptions) string
- func (pv *PropertyValidator) Validate(value interface{}, initialConditions ...string) (bool, []*Violation)
- type Range
- type RangeInt
- type RegionalVariantTranslation
- type SetConditionFrom
- type SetConditionIf
- type SetConditionOnType
- type SetConditionProperty
- type StringCharacters
- type StringContains
- type StringEndsWith
- type StringExactLength
- type StringGreaterThan
- type StringGreaterThanOrEqual
- type StringGreaterThanOrEqualOther
- type StringGreaterThanOther
- type StringLength
- type StringLessThan
- type StringLessThanOrEqual
- type StringLessThanOrEqualOther
- type StringLessThanOther
- type StringLowercase
- type StringMaxLength
- type StringMinLength
- type StringNoControlCharacters
- type StringNotBlank
- type StringNotEmpty
- type StringPattern
- type StringPresetPattern
- type StringStartsWith
- type StringUppercase
- type StringValidCardNumber
- type StringValidCountryCode
- type StringValidCurrencyCode
- type StringValidEmail
- type StringValidISODate
- type StringValidISODatetime
- type StringValidISODuration
- type StringValidJson
- type StringValidLanguageCode
- type StringValidTimezone
- type StringValidToken
- type StringValidUnicodeNormalization
- type StringValidUuid
- type TagAliases
- type TagHandler
- type Time
- type Translator
- type V8nTagStringOptions
- type ValidationError
- type Validator
- func (v *Validator) Clone() *Validator
- func (v *Validator) IsOrderedPropertyChecks() bool
- func (v *Validator) MarshalJSON() ([]byte, error)
- func (v *Validator) RequestQueryValidate(req *http.Request, initialConditions ...string) (bool, []*Violation, interface{})
- func (v *Validator) RequestQueryValidateInto(req *http.Request, value interface{}, initialConditions ...string) (bool, []*Violation, interface{})
- func (v *Validator) RequestValidate(req *http.Request, initialConditions ...string) (bool, []*Violation, interface{})
- func (v *Validator) RequestValidateInto(req *http.Request, value interface{}, initialConditions ...string) (bool, []*Violation, interface{})
- func (v *Validator) Validate(obj map[string]interface{}, initialConditions ...string) (bool, []*Violation)
- func (v *Validator) ValidateArrayOf(arr []interface{}, initialConditions ...string) (bool, []*Violation)
- func (v *Validator) ValidateInto(data []byte, value interface{}, initialConditions ...string) error
- func (v *Validator) ValidateReader(r io.Reader, initialConditions ...string) (bool, []*Violation, interface{})
- func (v *Validator) ValidateReaderInto(r io.Reader, value interface{}, initialConditions ...string) (bool, []*Violation, interface{})
- func (v *Validator) ValidateString(s string, initialConditions ...string) (bool, []*Violation, interface{})
- func (v *Validator) ValidateStringInto(s string, value interface{}, initialConditions ...string) (bool, []*Violation, interface{})
- type ValidatorContext
- func (vc *ValidatorContext) AddViolation(v *Violation)
- func (vc *ValidatorContext) AddViolationForCurrent(msg string, translate bool, codes ...interface{})
- func (vc *ValidatorContext) AncestorArrayIndex(level uint) (*int, bool)
- func (vc *ValidatorContext) AncestorPath(level uint) (*string, bool)
- func (vc *ValidatorContext) AncestorProperty(level uint) (interface{}, bool)
- func (vc *ValidatorContext) AncestorPropertyName(level uint) (*string, bool)
- func (vc *ValidatorContext) AncestorValue(level uint) (interface{}, bool)
- func (vc *ValidatorContext) AncestryIndex(level uint) (index int, max int, ok bool)
- func (vc *ValidatorContext) CeaseFurther()
- func (vc *ValidatorContext) CeaseFurtherIf(condition bool)
- func (vc *ValidatorContext) ClearCondition(condition string)
- func (vc *ValidatorContext) ClearGlobalCondition(condition string)
- func (vc *ValidatorContext) ClearParentCondition(condition string)
- func (vc *ValidatorContext) CurrentArrayIndex() *int
- func (vc *ValidatorContext) CurrentDepth() int
- func (vc *ValidatorContext) CurrentPath() string
- func (vc *ValidatorContext) CurrentProperty() interface{}
- func (vc *ValidatorContext) CurrentPropertyName() *string
- func (vc *ValidatorContext) CurrentValue() interface{}
- func (vc *ValidatorContext) IsCondition(condition string) bool
- func (vc *ValidatorContext) Language() string
- func (vc *ValidatorContext) Lock()
- func (vc *ValidatorContext) Region() string
- func (vc *ValidatorContext) SetCondition(condition string)
- func (vc *ValidatorContext) SetGlobalCondition(condition string)
- func (vc *ValidatorContext) SetParentCondition(condition string)
- func (vc *ValidatorContext) Stop()
- func (vc *ValidatorContext) TranslateFormat(format string, a ...interface{}) string
- func (vc *ValidatorContext) TranslateMessage(msg string) string
- func (vc *ValidatorContext) TranslateToken(token string) string
- func (vc *ValidatorContext) UnLock()
- func (vc *ValidatorContext) ValuesAncestry() []interface{}
- type ValidatorForOptions
- type VariablePropertyConstraint
- type Violation
Constants ¶
const ( // PresetAlpha checks for only alpha characters (use with StringPresetPattern) PresetAlpha = "alpha" // PresetAlphaNumeric checks for only alphanumeric characters (use with StringPresetPattern) PresetAlphaNumeric = "alphaNumeric" // PresetBarcode checks for a valid barcode (EAN, ISBN, ISSN, UPC) (use with StringPresetPattern) PresetBarcode = "barcode" // PresetBase64 checks for valid base64 encoded string (use with StringPresetPattern) PresetBase64 = "base64" // PresetBase64URL checks for valid base64 URL encoded string (use with StringPresetPattern) PresetBase64URL = "base64URL" // PresetCMYK checks for valid cmyk() color string (use with StringPresetPattern) PresetCMYK = "cmyk" // PresetCMYK300 checks for valid cmyk() color string (maximum 300%) (use with StringPresetPattern) PresetCMYK300 = "cmyk300" // PresetCard checks for valid card number (use with StringPresetPattern) PresetCard = "card" // PresetDUN14 checks for valid DUN-14 barcode (use with StringPresetPattern) PresetDUN14 = "DUN14" // PresetE164 checks for valid E.164 code (use with StringPresetPattern) PresetE164 = "e164" // PresetEAN checks for valid EAN barcode (EAN-8, 13, 14, 18 or 99) (use with StringPresetPattern) PresetEAN = "EAN" // PresetEAN13 checks for valid EAN-13 barcode (use with StringPresetPattern) PresetEAN13 = "EAN13" // PresetEAN14 checks for valid EAN-14 barcode (use with StringPresetPattern) PresetEAN14 = "EAN14" // PresetEAN18 checks for valid EAN-18 barcode (use with StringPresetPattern) PresetEAN18 = "EAN18" // PresetEAN8 checks for valid EAN-8 barcode (use with StringPresetPattern) PresetEAN8 = "EAN8" // PresetEAN99 checks for valid EAN-99 barcode (use with StringPresetPattern) PresetEAN99 = "EAN99" // PresetHexadecimal checks for valid hexadecimal string (use with StringPresetPattern) PresetHexadecimal = "hexadecimal" // PresetHsl checks for valid hsl() color string (use with StringPresetPattern) PresetHsl = "hsl" // PresetHsla checks for valid hsla() color string (use with StringPresetPattern) PresetHsla = "hsla" // PresetHtmlColor checks for valid HTML color string (use with StringPresetPattern) PresetHtmlColor = "htmlColor" // PresetISBN checks for valid ISBN barcode (ISBN-10 or 13) (use with StringPresetPattern) PresetISBN = "ISBN" // PresetISBN10 checks for valid ISBN-10 barcode (use with StringPresetPattern) PresetISBN10 = "ISBN10" // PresetISBN13 checks for valid ISBN-13 barcode (use with StringPresetPattern) PresetISBN13 = "ISBN13" // PresetISSN checks for valid ISSN barcode (ISSN-8 or 13) (use with StringPresetPattern) PresetISSN = "ISSN" // PresetISSN13 checks for valid ISSN-13 barcode (use with StringPresetPattern) PresetISSN13 = "ISSN13" // PresetISSN8 checks for valid ISSN-8 barcode (use with StringPresetPattern) PresetISSN8 = "ISSN8" // PresetInteger checks for valid integer string (chars 0-9) (use with StringPresetPattern) PresetInteger = "integer" // PresetNumeric checks for valid numeric string (use with StringPresetPattern) PresetNumeric = "numeric" // PresetNumericE checks for valid numeric string allowing scientific notation (use with StringPresetPattern) PresetNumericE = "numeric+e" // PresetNumericX checks for valid numeric string allowing scientific notation plus "Inf" and "NaN" (use with StringPresetPattern) PresetNumericX = "numeric+x" // PresetPublication checks for valid publication barcode (ISBN or ISSN) (use with StringPresetPattern) PresetPublication = "publication" // PresetRgb checks for valid rgb() color string (use with StringPresetPattern) PresetRgb = "rgb" // PresetRgbIcc checks for valid rgb-icc() color string (use with StringPresetPattern) PresetRgbIcc = "rgb-icc" // PresetRgba checks for valid rgba() color string (use with StringPresetPattern) PresetRgba = "rgba" // PresetULID checks for valid ULID code (use with StringPresetPattern) PresetULID = "ULID" // PresetUPC checks for valid UPC barcode (UPC-A or UPC-E) (use with StringPresetPattern) PresetUPC = "UPC" // PresetUPCA checks for valid UPC-A barcode (use with StringPresetPattern) PresetUPCA = "UPC-A" // PresetUPCE checks for valid UPC-E barcode (use with StringPresetPattern) PresetUPCE = "UPC-E" // PresetUUID checks for valid UUID (upper or lower hex chars) (use with StringPresetPattern) PresetUUID = "UUID" // PresetUUID1 checks for valid UUID Version 1 (upper or lower hex chars) (use with StringPresetPattern) PresetUUID1 = "UUID1" // PresetUUID2 checks for valid UUID Version 2 (upper or lower hex chars) (use with StringPresetPattern) PresetUUID2 = "UUID2" // PresetUUID3 checks for valid UUID Version 3 (upper or lower hex chars) (use with StringPresetPattern) PresetUUID3 = "UUID3" // PresetUUID4 checks for valid UUID Version 4 (upper or lower hex chars) (use with StringPresetPattern) PresetUUID4 = "UUID4" // PresetUUID5 checks for valid UUID Version 5 (upper or lower hex chars) (use with StringPresetPattern) PresetUUID5 = "UUID5" // PresetUuid checks for valid UUID (lower hex chars only) (use with StringPresetPattern) PresetUuid = "uuid" // PresetUuid1 checks for valid UUID Version 1 (lower hex chars only) (use with StringPresetPattern) PresetUuid1 = "uuid1" // PresetUuid2 checks for valid UUID Version 2 (lower hex chars only) (use with StringPresetPattern) PresetUuid2 = "uuid2" // PresetUuid3 checks for valid UUID Version 3 (lower hex chars only) (use with StringPresetPattern) PresetUuid3 = "uuid3" // PresetUuid4 checks for valid UUID Version 4 (lower hex chars only) (use with StringPresetPattern) PresetUuid4 = "uuid4" // PresetUuid5 checks for valid UUID Version 5 (lower hex chars only) (use with StringPresetPattern) PresetUuid5 = "uuid5" )
const ( // CodeValueCannotBeNull is the violation code when a value is null CodeValueCannotBeNull = 42211 // CodeValueExpectedType is the violation code when a value is of the incorrect type CodeValueExpectedType = 42212 // CodeValueMustBeObject is the violation code when a value is expected to be an object but is not CodeValueMustBeObject = 42213 // CodeValueMustBeArray is the violation code when a value is expected to be an array but is not CodeValueMustBeArray = 42214 // CodeValueMustBeObjectOrArray is the violation code when a value is expected to be an object or array but is neither CodeValueMustBeObjectOrArray = 42215 // CodePropertyObjectValidatorError is the violation code when an object validator disallows both arrays and objects CodePropertyObjectValidatorError = 42216 // CodePropertyConstraintFail is the violation code when a value fails a constraint CodePropertyConstraintFail = 42299 )
const ( // CodeRequestQueryParamMultiNotAllowed is the violation code when a query param is specified more than once but may not be CodeRequestQueryParamMultiNotAllowed = 40010 // CodeRequestQueryParamInvalidType is the violation code when a query param value is an incorrect type CodeRequestQueryParamInvalidType = 40011 )
const ( ISO4217TestCurrencyCode = "XTS" ISO4217TestCurrencyCodeNumeric = "963" ISO4217NoCurrencyCode = "XXX" ISO4217NoCurrencyCodeNumeric = "999" )
const ( // CodeUnableToDecode is the violation code when the validator is unable to decode the JSON CodeUnableToDecode = 40001 // CodeNotJsonNull is the violation code when the validator finds JSON null but Validator.AllowNullJson is false CodeNotJsonNull = 40002 // CodeNotJsonArray is the violation code when the validator is expecting a JSON array but the JSON is not an array CodeNotJsonArray = 42200 // CodeNotJsonObject is the violation code when the validator is expecting a JSON object but the JSON is not an object CodeNotJsonObject = 42201 // CodeExpectedJsonArray is the violation code when the validator is expecting a JSON array but the JSON is an object CodeExpectedJsonArray = 42202 // CodeExpectedJsonObject is the violation code when the validator is expecting a JSON object but the JSON is an array CodeExpectedJsonObject = 40003 // CodeErrorReading is the violation code when the validator errors trying to read a request (or reader) CodeErrorReading = 40004 // CodeErrorUnmarshall is the violation code when the validator errors trying to unmarshal successfully validated data into a target struct (check your validator matches the struct!) CodeErrorUnmarshall = 40005 // CodeRequestBodyEmpty is the violation code when the validator attempts to read an empty request (or reader) CodeRequestBodyEmpty = 40006 // CodeUnableToDecodeRequest is the violation code when the validator errors trying to decode a request JSON CodeUnableToDecodeRequest = 40007 // CodeRequestBodyNotJsonNull is the violation code when the validator finds a JSON null request but Validator.AllowNullJson is false CodeRequestBodyNotJsonNull = 40008 // CodeRequestBodyNotJsonArray is the violation code when the validator is expecting a JSON array request but the JSON is not an array CodeRequestBodyNotJsonArray = 42203 // CodeRequestBodyNotJsonObject is the violation code when the validator is expecting a JSON object request but the JSON is not an object CodeRequestBodyNotJsonObject = 42204 // CodeRequestBodyExpectedJsonArray is the violation code when the validator is expecting a JSON array request but the JSON is an object CodeRequestBodyExpectedJsonArray = 42205 // CodeRequestBodyExpectedJsonObject is the violation code when the validator is expecting a JSON object request but the JSON is an array CodeRequestBodyExpectedJsonObject = 40009 // CodeArrayElementMustBeObject is the violation code when the validator is expecting a JSON array element to be an object CodeArrayElementMustBeObject = 42206 // CodeMissingProperty is the violation code when the validator detects a missing property CodeMissingProperty = 42207 // CodeUnwantedProperty is the violation code when the validator detects a property that is unwanted (i.e the property is known but should not be present under current conditions) CodeUnwantedProperty = 42208 // CodeUnknownProperty is the violation code when the validator detects an unknown property (and Validator.IgnoreUnknownProperties is false) CodeUnknownProperty = 42209 // CodeInvalidProperty is the violation code when the validator detects an known property that is invalid under current conditions (e.g. with specified other properties present) CodeInvalidProperty = 42210 // CodeInvalidPropertyName is the violation code when the validator detects a variable property with an invalid name CodeInvalidPropertyName = 42217 // CodePropertyValueMustBeObject is the violation code when the validator detects property value that is ecpected to be an object but is not CodePropertyValueMustBeObject = 42218 // CodePropertyRequiredWhen is the violation code when the validator detects a missing property that is required under current conditions CodePropertyRequiredWhen = 42219 // CodePropertyUnwantedWhen is the violation code when the validator detects a property present that is unwanted under current conditions CodePropertyUnwantedWhen = 42220 // CodeArrayElementMustNotBeNull is the violation code when the validator detects a null array element but is null is not allowed (i.e Validator.AllowNullItems is false) CodeArrayElementMustNotBeNull = 42221 // CodeOnlyProperty is the violation code when the validator detects a property that is specified as being an only property but has other properties present CodeOnlyProperty = 42222 // CodeValidatorConstraintFail is the violation code when the validator fails one of its Validator.Constraints CodeValidatorConstraintFail = 42298 )
const (
// NoMessage is a special message used by constraints to indicate no message rather than default message
NoMessage = "[NO_MESSAGE]"
)
Variables ¶
var ( // UnicodeBMP is a unicode.RangeTable that represents the Unicode BMP (Basic Multilingual Plane) // // For use with StringCharacters constraint UnicodeBMP = unicode.RangeTable{ R16: []unicode.Range16{ {0x0000, 0xffff, 1}, }, } // UnicodeSMP is a unicode.RangeTable that represents the Unicode SMP (Supplementary Multilingual Plane) // // For use with StringCharacters constraint UnicodeSMP = unicode.RangeTable{ R32: []unicode.Range32{ {0x10000, 0x1ffff, 1}, }, } // UnicodeSIP is a unicode.RangeTable that represents the Unicode SIP (Supplementary Ideographic Plane) // // For use with StringCharacters constraint UnicodeSIP = unicode.RangeTable{ R32: []unicode.Range32{ {0x20000, 0x2ffff, 1}, }, } )
var DefaultFallbackLanguages = map[string]string{}
DefaultFallbackLanguages is a map of language codes with their fallback language code
var DefaultLanguage = "en"
DefaultLanguage is the default language used by the default I18nProvider
Languages provided are "de", "en", "es", "fr" & "it"
var DefaultRegion = ""
DefaultRegion is the default region used by the default I18nProvider
Functions ¶
func ClearCustomTagTokens ¶
func ClearCustomTagTokens()
ClearCustomTagTokens clears any custom tag tokens registered using RegisterCustomTagToken
func ClearCustomTags ¶
func ClearCustomTags()
ClearCustomTags clears any registered custom tags that were registered using RegisterCustomTag
func ClearTagTokenAliases ¶
func ClearTagTokenAliases()
ClearTagTokenAliases clears any tag aliases registered using RegisterTagTokenAlias / RegisterTagTokenAliases
func ConstraintsRegistryHas ¶
ConstraintsRegistryHas is provided for test purposes - so the constraints registry can be checked to see if a specific constraint name has been registered
func ConstraintsRegistryReset ¶
func ConstraintsRegistryReset()
ConstraintsRegistryReset is provided for test purposes - so the constraints registry can be cleared of all registered constraints (and reset to just the Valix common constraints)
func PropertiesRepoClear ¶
func PropertiesRepoClear()
PropertiesRepoClear clears the properties repository
func PropertiesRepoPanics ¶
func PropertiesRepoPanics(panics bool)
PropertiesRepoPanics sets whether the properties repository panics when asked for a common property that does not exist
func ReRegisterConstraint ¶
func ReRegisterConstraint(constraint Constraint)
ReRegisterConstraint registers a Constraint for use by ValidatorFor
For example:
ReRegisterConstraint(&MyConstraint{})
will register the named constraint `MyConstraint` (using reflect to determine the name) which can then be used in a tag, e.g.
type MyRequest struct {
MyProperty string `json:"my_pty" v8n:"constraints:MyConstraint"`
}
Use ReRegisterNamedConstraint to register a specific name (without using reflect to determine name
If the constraint is already registered it is overwritten (this function will never panic)
func ReRegisterConstraints ¶
func ReRegisterConstraints(constraints ...Constraint)
ReRegisterConstraints registers multiple constraints
If any of the constraints are already registered they are overwritten (this function will never panic)
func ReRegisterNamedConstraint ¶
func ReRegisterNamedConstraint(name string, constraint Constraint)
ReRegisterNamedConstraint registers a Constraint for use by ValidatorFor with a specific name (or alias)
For example:
ReRegisterNamedConstraint("myYes", &MyConstraint{SomeFlag: true})
ReRegisterNamedConstraint("myNo", &MyConstraint{SomeFlag: false})
will register the two named constraints (with different default settings) which can then be used in a tag, e.g.
type MyRequest struct {
MyProperty1 string `json:"my_pty_1" v8n:"constraints:myYes"`
MyProperty2 string `json:"my_pty_2" v8n:"constraints:myNo"`
}
If the constraint is already registered it is overwritten (this function will never panic)
func ReRegisterNamedConstraints ¶
func ReRegisterNamedConstraints(constraints map[string]Constraint)
ReRegisterNamedConstraints registers multiple named constraints
If any of the constraints are already registered they are overwritten (this function will never panic)
func RegisterConstraint ¶
func RegisterConstraint(constraint Constraint)
RegisterConstraint registers a Constraint for use by ValidatorFor
For example:
RegisterConstraint(&MyConstraint{})
will register the named constraint `MyConstraint` (using reflect to determine the name) which can then be used in a tag, e.g.
type MyRequest struct {
MyProperty string `json:"my_pty" v8n:"constraints:MyConstraint"`
}
Use RegisterNamedConstraint to register a specific name (without using reflect to determine name
Note: this function will panic if the constraint is already registered - use ReRegisterConstraint for non-panic behaviour where you don't mind the constraint registration being overwritten
func RegisterConstraints ¶
func RegisterConstraints(constraints ...Constraint)
RegisterConstraints registers multiple constraints
Note: this function will panic if the constraint is already registered - use ReRegisterConstraints for non-panic behaviour where you don't mind the constraint registration being overwritten
func RegisterCustomTag ¶
func RegisterCustomTag(tag string, handler TagHandler)
RegisterCustomTag registers a custom tag - for use when building validators from structs using valix.ValidatorFor, for example...
RegisterCustomTag("custom", myTagHandler)
and then use the custom tag...
type MyStruct struct {
Foo string `custom:"<custom_value>"`
}
and then build validator for struct...
validator, err := valix.ValidatorFor(MyStruct{}, nil)
will call the custom tag handler when building the validator
func RegisterCustomTagToken ¶
func RegisterCustomTagToken(token string, handler CustomTagTokenHandler)
RegisterCustomTagToken registers a custom tag token handler - registered custom tag tokens can be used within the `v8n` tag
Example:
RegisterCustomTagToken("my_token", myCustomTokenHandler)
and then use the custom tag token...
type MyStruct struct {
Foo string `json:"foo" v8n:"my_token: hello"`
}
func RegisterNamedConstraint ¶
func RegisterNamedConstraint(name string, constraint Constraint)
RegisterNamedConstraint registers a Constraint for use by ValidatorFor with a specific name (or alias)
For example:
RegisterNamedConstraint("myYes", &MyConstraint{SomeFlag: true})
RegisterNamedConstraint("myNo", &MyConstraint{SomeFlag: false})
will register the two named constraints (with different settings) which can then be used in a tag, e.g.
type MyRequest struct {
MyProperty1 string `json:"my_pty_1" v8n:"constraints:myYes"`
MyProperty2 string `json:"my_pty_2" v8n:"constraints:myNo"`
}
Note: this function will panic if the constraint is already registered - use ReRegisterNamedConstraint for non-panic behaviour where you don't mind the constraint registration being overwritten
func RegisterNamedConstraints ¶
func RegisterNamedConstraints(constraints map[string]Constraint)
RegisterNamedConstraints registers multiple named constraints
Note: this function will panic if the constraint is already registered - use ReRegisterNamedConstraints for non-panic behaviour where you don't mind the constraint registration being overwritten
func RegisterPreset ¶
RegisterPreset registers a preset pattern for use by the StringPresetPattern constraint
* the `asConstraint` arg, if true, means the preset is also registered as a named constraint and is available for use as a `v8n` constraint tag
func RegisterPresetPattern ¶
func RegisterPresetPattern(token string, rx *regexp.Regexp, message string, postCheck PostPatternChecker, asConstraint bool)
RegisterPresetPattern registers a preset pattern for use by the StringPresetPattern constraint
* the `token` arg specifies the token for the preset (as used by the StringPresetPattern.Preset field)
* the `rx` arg specifies the *regexp.Regexp that must be matched (if nil, a match anything regexp is used)
* the `message` arg specifies the message for the preset
* the `postCheck` is any post pattern checking that needs to be satisfied
* the `asConstraint` arg, if true, means the preset is also registered as a named constraint and is available for use as a `v8n` constraint tag
func RegisterProperties ¶
func RegisterProperties(properties Properties)
RegisterProperties registers common properties in the properties repository
The properties repository is used by validators to lookup common properties when:
- a property validator is nil, e.g. v := valix.Validator{ Properties: valix.Properties{ "foo": nil, }, }
- a struct tag of `v8n-as` is used, e.g. type MyStruct struct { Foo string `json:"foo" v8n-as:""` }
or...
type MyStruct struct {
FooId string `json:"fooId" v8n-as:"id"`
}
func RegisterTagTokenAlias ¶
RegisterTagTokenAlias registers a tag alias - a tag alias can be used in the `v8n` tag to specify multiple tokens using a single alias
Example:
RegisterTagTokenAlias("mnnne", "mandatory,notNull,&StringNotEmpty{}"
and the use the alias with the `v8n` tag...
type MyStruct struct {
Foo string `json:"foo" v8n:"$mnnne, &StringNotBlank{}"`
}
would be the equivalent of...
type MyStruct struct {
Foo string `json:"foo" v8n:"mandatory,notNull,&StringNotEmpty{}, &StringNotBlank{}"`
}
func RegisterTagTokenAliases ¶
func RegisterTagTokenAliases(aliases TagAliases)
RegisterTagTokenAliases register multiple tag aliases - see RegisterTagTokenAlias
func SortViolationsByPathAndProperty ¶
func SortViolationsByPathAndProperty(violations []*Violation)
SortViolationsByPathAndProperty is a utility function for sorting violations
Types ¶
type ArrayConditionalConstraint ¶
type ArrayConditionalConstraint struct {
// When is the special token denoting the array condition on which the wrapped constraint is to be checked
//
// The special token can be one of:
//
// * "first" - when the array item is the first
//
// * "!first" - when the array item is not the first
//
// * "last" - when the array item is the last
//
// * "!last" - when the array item is not the last
//
// * "%n" - when the modulus n of the array index is zero
//
// * ">n" - when the array index is greater than n
//
// * "<n" - when the array index is less than n
//
// * "n" - when the array index is n
When string
// Ancestry is ancestry depth at which to obtain the current array index information
//
// Note: the ancestry level is only for arrays in the object tree (and does not need to include other levels).
// Therefore, by default the value is 0 (zero) - which means the last encountered array
Ancestry uint
Constraint Constraint
}
ArrayConditionalConstraint is a special constraint that wraps another constraint - but the wrapped constraint is only checked when the specified array condition is met (see When property)
func (*ArrayConditionalConstraint) Check ¶
func (c *ArrayConditionalConstraint) Check(v interface{}, vcx *ValidatorContext) (bool, string)
func (*ArrayConditionalConstraint) GetMessage ¶
func (c *ArrayConditionalConstraint) GetMessage(tcx I18nContext) string
func (*ArrayConditionalConstraint) MarshalJSON ¶
func (c *ArrayConditionalConstraint) MarshalJSON() ([]byte, error)
func (*ArrayConditionalConstraint) UnmarshalJSON ¶
func (c *ArrayConditionalConstraint) UnmarshalJSON(data []byte) error
type ArrayDistinctProperty ¶
type ArrayDistinctProperty struct {
// the name of the property (in each array element object) to check for distinct (uniqueness)
PropertyName string `v8n:"default"`
// whether to ignore null property values in the array
IgnoreNulls bool
// whether uniqueness is case in-insensitive (for string value properties)
IgnoreCase bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
ArrayDistinctProperty constraint to check each object element in an array has a specified property that is distinct
This differs from ArrayUnique, which checks for unique items in the array, whereas ArrayDistinctProperty checks objects within an array to ensure that a specific property is unique
func (*ArrayDistinctProperty) Check ¶
func (c *ArrayDistinctProperty) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*ArrayDistinctProperty) GetMessage ¶
func (c *ArrayDistinctProperty) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type ArrayOf ¶
type ArrayOf struct {
// the type to check for each item (use Type values)
Type string `v8n:"default"`
// whether to allow null items in the array
AllowNullElement bool
// is an optional list of constraints that each array element must satisfy
Constraints Constraints
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
ArrayOf constraint to check each element in an array value is of the correct type
func (*ArrayOf) Check ¶
func (c *ArrayOf) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*ArrayOf) GetMessage ¶
func (c *ArrayOf) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type ArrayUnique ¶
type ArrayUnique struct {
// whether to ignore null items in the array
IgnoreNulls bool `v8n:"default"`
// whether uniqueness is case in-insensitive (for string elements)
IgnoreCase bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
ArrayUnique constraint to check each element in an array value is unique
func (*ArrayUnique) Check ¶
func (c *ArrayUnique) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*ArrayUnique) GetMessage ¶
func (c *ArrayUnique) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type Check ¶
type Check func(value interface{}, vcx *ValidatorContext, this *CustomConstraint) (passed bool, message string)
Check function signature for custom constraints
type Conditional ¶
type Conditional interface {
MeetsConditions(vcx *ValidatorContext) bool
}
type ConditionalConstraint ¶
type ConditionalConstraint struct {
// When is the condition tokens that determine when the wrapped constraint is checked
When Conditions
// Others is the others expression to be evaluated to determine when the wrapped constraint is checked
Others OthersExpr
// Constraint is the wrapped constraint
Constraint Constraint
// FailNotMet specifies that the conditional constraint should fail if the conditions are not met
//
// By default, if the conditions are not met the conditional constraint passes (without calling the wrapped constraint)
FailNotMet bool
// NotMetMessage is the message used when FailNotMet is set and the conditions are not met
NotMetMessage string
}
ConditionalConstraint is a special constraint that wraps another constraint - but the wrapped constraint is only checked when the specified when condition is met
func (*ConditionalConstraint) Check ¶
func (c *ConditionalConstraint) Check(v interface{}, vcx *ValidatorContext) (bool, string)
func (*ConditionalConstraint) GetMessage ¶
func (c *ConditionalConstraint) GetMessage(tcx I18nContext) string
func (*ConditionalConstraint) MeetsConditions ¶
func (c *ConditionalConstraint) MeetsConditions(vcx *ValidatorContext) bool
type ConditionalVariant ¶
type ConditionalVariant struct {
// WhenConditions is the condition tokens that determine when this variant is used
WhenConditions Conditions
Constraints Constraints
Properties Properties
// ConditionalVariants is any descendant conditional variants
ConditionalVariants ConditionalVariants
}
ConditionalVariant represents the condition(s) under which to use a specific variant Validator
func (*ConditionalVariant) Clone ¶
func (src *ConditionalVariant) Clone() *ConditionalVariant
type ConditionalVariants ¶
type ConditionalVariants []*ConditionalVariant
ConditionalVariants type used by Validator.ConditionalVariants
func (ConditionalVariants) Clone ¶
func (src ConditionalVariants) Clone() ConditionalVariants
type Conditions ¶
type Conditions []string
func (Conditions) Clone ¶
func (src Conditions) Clone() Conditions
type Constraint ¶
type Constraint interface {
// Check the constraint against a given value
Check(value interface{}, vcx *ValidatorContext) (passed bool, message string)
// GetMessage returns the actual message for the constraint
//
// This method is required so that any documenting functionality can determine
// the constraint message without having to actually run the constraint
GetMessage(tcx I18nContext) string
}
Constraint is the interface for all validation constraints on a property and object
func GetRegisteredConstraint ¶
func GetRegisteredConstraint(name string) (Constraint, bool)
GetRegisteredConstraint returns a previously registered constraint
type ConstraintSet ¶
type ConstraintSet struct {
// Constraints is the slice of constraints within the set
Constraints Constraints `v8n:"default"`
// when set to true, OneOf specifies that the constraint set should pass just one of
// the contained constraints (rather than all of them)
OneOf bool
// Message is the violation message to be used if any of the constraints fail
//
// If the message is empty, the message from the first failing contained constraint is used
Message string
// Stop when set to true, prevents further validation checks on the property if this constraint set fails
Stop bool
}
ConstraintSet is a constraint that contains other constraints
The contained constraints are checked sequentially but the overall set stops on the first failing constraint
func (*ConstraintSet) Check ¶
func (c *ConstraintSet) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements the Constraint.Check and checks the constraints within the set
func (*ConstraintSet) GetMessage ¶
func (c *ConstraintSet) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
func (*ConstraintSet) MarshalJSON ¶
func (c *ConstraintSet) MarshalJSON() ([]byte, error)
func (*ConstraintSet) UnmarshalJSON ¶
func (c *ConstraintSet) UnmarshalJSON(data []byte) error
type Constraints ¶
type Constraints []Constraint
Constraints type used by Validator.Constraints and PropertyValidator.Constraints
func (Constraints) Clone ¶
func (src Constraints) Clone() Constraints
func (Constraints) MarshalJSON ¶
func (cs Constraints) MarshalJSON() ([]byte, error)
func (*Constraints) UnmarshalJSON ¶
func (cs *Constraints) UnmarshalJSON(data []byte) error
type CustomConstraint ¶
CustomConstraint is a constraint that can declared on the fly and implements the Constraint interface
func NewCustomConstraint ¶
func NewCustomConstraint(check Check, message string) *CustomConstraint
NewCustomConstraint Creates a custom Constraint which uses the supplied Check function
func (*CustomConstraint) Check ¶
func (c *CustomConstraint) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements the Constraint.Check and calls the CustomConstraint.CheckFunc
func (*CustomConstraint) GetMessage ¶
func (c *CustomConstraint) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type CustomTagTokenHandler ¶
type CustomTagTokenHandler interface {
Handle(token string, hasValue bool, tokenValue string, pv *PropertyValidator, propertyName string, fieldName string) error
}
CustomTagTokenHandler is the interface for handling custom tag tokens (i.e. custom tokens in the `v8n` tag)
type DatetimeDayOfWeek ¶
type DatetimeDayOfWeek struct {
// is the allowed days (of the week) expressed as a string of allowed week day numbers (in any order)
//
// Where 0 = Sunday, e.g. "06" (or "60") allows Sunday or Saturday
//
// or to allow only 'working days' of the week - "12345"
Days string `v8n:"default"`
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
DatetimeDayOfWeek checks that a date (represented as string or time.Time) is an allowed day of the week
func (*DatetimeDayOfWeek) Check ¶
func (c *DatetimeDayOfWeek) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*DatetimeDayOfWeek) GetMessage ¶
func (c *DatetimeDayOfWeek) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type DatetimeFuture ¶
type DatetimeFuture struct {
// when set to true, excludes the time when comparing
//
// Note: This also excludes the effect of any timezone offsets specified in either of the compared values
ExcTime bool `v8n:"default"`
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
DatetimeFuture constraint checks that a datetime/date (represented as string or time.Time) is in the future
func (*DatetimeFuture) Check ¶
func (c *DatetimeFuture) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*DatetimeFuture) GetMessage ¶
func (c *DatetimeFuture) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type DatetimeFutureOrPresent ¶
type DatetimeFutureOrPresent struct {
// when set to true, excludes the time when comparing
//
// Note: This also excludes the effect of any timezone offsets specified in either of the compared values
ExcTime bool `v8n:"default"`
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
DatetimeFutureOrPresent constraint checks that a datetime/date (represented as string or time.Time) is in the future or present
func (*DatetimeFutureOrPresent) Check ¶
func (c *DatetimeFutureOrPresent) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*DatetimeFutureOrPresent) GetMessage ¶
func (c *DatetimeFutureOrPresent) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type DatetimeGreaterThan ¶
type DatetimeGreaterThan struct {
// the value to compare against (a string representation of date or datetime in ISO format)
Value string `v8n:"default"`
// when set to true, excludes the time when comparing
//
// Note: This also excludes the effect of any timezone offsets specified in either of the compared values
ExcTime bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
DatetimeGreaterThan constraint to check that a date/time (as an ISO string) value is greater than a specified value
Note: this constraint is strict - if either of the compared values is not a valid ISO datetime then this constraint fails
func (*DatetimeGreaterThan) Check ¶
func (c *DatetimeGreaterThan) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*DatetimeGreaterThan) GetMessage ¶
func (c *DatetimeGreaterThan) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type DatetimeGreaterThanOrEqual ¶
type DatetimeGreaterThanOrEqual struct {
// the value to compare against (a string representation of date or datetime in ISO format)
Value string `v8n:"default"`
// when set to true, excludes the time when comparing
//
// Note: This also excludes the effect of any timezone offsets specified in either of the compared values
ExcTime bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
DatetimeGreaterThanOrEqual constraint to check that a date/time (as an ISO string) value is greater than or equal to a specified value
Note: this constraint is strict - if either of the compared values is not a valid ISO datetime then this constraint fails
func (*DatetimeGreaterThanOrEqual) Check ¶
func (c *DatetimeGreaterThanOrEqual) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*DatetimeGreaterThanOrEqual) GetMessage ¶
func (c *DatetimeGreaterThanOrEqual) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type DatetimeGreaterThanOrEqualOther ¶
type DatetimeGreaterThanOrEqualOther struct {
// the property name of the other value to compare against
//
// Note: the PropertyName can also be JSON dot notation path - where leading dots allow traversal up
// the object tree and names, separated by dots, allow traversal down the object tree.
// A single dot at start is equivalent to no starting dot (i.e. a property name at the same level)
PropertyName string `v8n:"default"`
// when set to true, excludes the time when comparing
//
// Note: This also excludes the effect of any timezone offsets specified in either of the compared values
ExcTime bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
DatetimeGreaterThanOrEqualOther constraint to check that a date/time (as an ISO string) value is greater than or equal to another named property value
Note: this constraint is strict - if either of the compared values is not a valid ISO datetime then this constraint fails
func (*DatetimeGreaterThanOrEqualOther) Check ¶
func (c *DatetimeGreaterThanOrEqualOther) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*DatetimeGreaterThanOrEqualOther) GetMessage ¶
func (c *DatetimeGreaterThanOrEqualOther) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type DatetimeGreaterThanOther ¶
type DatetimeGreaterThanOther struct {
// the property name of the other value to compare against
//
// Note: the PropertyName can also be JSON dot notation path - where leading dots allow traversal up
// the object tree and names, separated by dots, allow traversal down the object tree.
// A single dot at start is equivalent to no starting dot (i.e. a property name at the same level)
PropertyName string `v8n:"default"`
// when set to true, excludes the time when comparing
//
// Note: This also excludes the effect of any timezone offsets specified in either of the compared values
ExcTime bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
DatetimeGreaterThanOther constraint to check that a date/time (as an ISO string) value is greater than another named property value
Note: this constraint is strict - if either of the compared values is not a valid ISO datetime then this constraint fails
func (*DatetimeGreaterThanOther) Check ¶
func (c *DatetimeGreaterThanOther) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*DatetimeGreaterThanOther) GetMessage ¶
func (c *DatetimeGreaterThanOther) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type DatetimeLessThan ¶
type DatetimeLessThan struct {
// the value to compare against (a string representation of date or datetime in ISO format)
Value string `v8n:"default"`
// when set to true, excludes the time when comparing
//
// Note: This also excludes the effect of any timezone offsets specified in either of the compared values
ExcTime bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
DatetimeLessThan constraint to check that a date/time (as an ISO string) value is less than a specified value
Note: this constraint is strict - if either of the compared values is not a valid ISO datetime then this constraint fails
func (*DatetimeLessThan) Check ¶
func (c *DatetimeLessThan) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*DatetimeLessThan) GetMessage ¶
func (c *DatetimeLessThan) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type DatetimeLessThanOrEqual ¶
type DatetimeLessThanOrEqual struct {
// the value to compare against (a string representation of date or datetime in ISO format)
Value string `v8n:"default"`
// when set to true, excludes the time when comparing
//
// Note: This also excludes the effect of any timezone offsets specified in either of the compared values
ExcTime bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
DatetimeLessThanOrEqual constraint to check that a date/time (as an ISO string) value is less than or equal to a specified value
Note: this constraint is strict - if either of the compared values is not a valid ISO datetime then this constraint fails
func (*DatetimeLessThanOrEqual) Check ¶
func (c *DatetimeLessThanOrEqual) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*DatetimeLessThanOrEqual) GetMessage ¶
func (c *DatetimeLessThanOrEqual) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type DatetimeLessThanOrEqualOther ¶
type DatetimeLessThanOrEqualOther struct {
// the property name of the other value to compare against
//
// Note: the PropertyName can also be JSON dot notation path - where leading dots allow traversal up
// the object tree and names, separated by dots, allow traversal down the object tree.
// A single dot at start is equivalent to no starting dot (i.e. a property name at the same level)
PropertyName string `v8n:"default"`
// when set to true, excludes the time when comparing
//
// Note: This also excludes the effect of any timezone offsets specified in either of the compared values
ExcTime bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
DatetimeLessThanOrEqualOther constraint to check that a date/time (as an ISO string) value is less than or equal to another named property value
Note: this constraint is strict - if either of the compared values is not a valid ISO datetime then this constraint fails
func (*DatetimeLessThanOrEqualOther) Check ¶
func (c *DatetimeLessThanOrEqualOther) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*DatetimeLessThanOrEqualOther) GetMessage ¶
func (c *DatetimeLessThanOrEqualOther) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type DatetimeLessThanOther ¶
type DatetimeLessThanOther struct {
// the property name of the other value to compare against
//
// Note: the PropertyName can also be JSON dot notation path - where leading dots allow traversal up
// the object tree and names, separated by dots, allow traversal down the object tree.
// A single dot at start is equivalent to no starting dot (i.e. a property name at the same level)
PropertyName string `v8n:"default"`
// when set to true, excludes the time when comparing
//
// Note: This also excludes the effect of any timezone offsets specified in either of the compared values
ExcTime bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
DatetimeLessThanOther constraint to check that a date/time (as an ISO string) value is less than another named property value
Note: this constraint is strict - if either of the compared values is not a valid ISO datetime then this constraint fails
func (*DatetimeLessThanOther) Check ¶
func (c *DatetimeLessThanOther) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*DatetimeLessThanOther) GetMessage ¶
func (c *DatetimeLessThanOther) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type DatetimePast ¶
type DatetimePast struct {
// when set to true, excludes the time when comparing
//
// Note: This also excludes the effect of any timezone offsets specified in either of the compared values
ExcTime bool `v8n:"default"`
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
DatetimePast constraint checks that a datetime/date (represented as string or time.Time) is in the past
func (*DatetimePast) Check ¶
func (c *DatetimePast) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*DatetimePast) GetMessage ¶
func (c *DatetimePast) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type DatetimePastOrPresent ¶
type DatetimePastOrPresent struct {
// when set to true, excludes the time when comparing
//
// Note: This also excludes the effect of any timezone offsets specified in either of the compared values
ExcTime bool `v8n:"default"`
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
DatetimePastOrPresent constraint checks that a datetime/date (represented as string or time.Time) is in the past or present
func (*DatetimePastOrPresent) Check ¶
func (c *DatetimePastOrPresent) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*DatetimePastOrPresent) GetMessage ¶
func (c *DatetimePastOrPresent) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type DatetimeRange ¶
type DatetimeRange struct {
// is the minimum datetime/date (if this is empty, then no minimum check is performed)
Minimum string
// is the maximum datetime/date (if this is empty, then no maximum check is performed)
Maximum string
// when set to true, excludes the time when comparing
//
// Note: This also excludes the effect of any timezone offsets specified in either of the compared values
ExcTime bool
// if set to true, ExclusiveMin specifies the minimum value is exclusive
ExclusiveMin bool
// if set to true, ExclusiveMax specifies the maximum value is exclusive
ExclusiveMax bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
DatetimeRange constraint checks that a datetime/date (represented as string or time.Time) is within a specified range
func (*DatetimeRange) Check ¶
func (c *DatetimeRange) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*DatetimeRange) GetMessage ¶
func (c *DatetimeRange) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type DatetimeTimeOfDayRange ¶
type DatetimeTimeOfDayRange struct {
// is the minimum time of day (if this is empty, then no minimum check is performed)
Minimum string
// is the maximum time of day (if this is empty, then no maximum check is performed)
Maximum string
// if set to true, ExclusiveMin specifies the minimum value is exclusive
ExclusiveMin bool
// if set to true, ExclusiveMax specifies the maximum value is exclusive
ExclusiveMax bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
DatetimeTimeOfDayRange constraint checks that a datetime (represented as string or time.Time) is within a specified time of day range
func (*DatetimeTimeOfDayRange) Check ¶
func (c *DatetimeTimeOfDayRange) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*DatetimeTimeOfDayRange) GetMessage ¶
func (c *DatetimeTimeOfDayRange) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type DatetimeTolerance ¶
type DatetimeTolerance struct {
// the value to compare against (a string representation of date or datetime in ISO format)
Value string `v8n:"default"`
// the tolerance duration amount - which can be positive, negative or zero
//
// For negative values, this is the maximum duration into the past
//
// For positive values, this is the maximum duration into the future
//
// Note: If the value is zero then the behaviour is assumed to be "same" - but is then dependent on the unit
// specified. For example, if the Duration is zero and the Unit is specified as "year" then this constraint
// will check the same year
Duration int64
// is the string token specifying the unit in which the Duration is measured
//
// this can be "millennium", "century", "decade", "year", "month", "week", "day",
// "hour", "min", "sec" or "milli" (millisecond), "micro" (microsecond) or "nano" (nanosecond)
//
// Note: if this is empty, then "day" is assumed. If the token is invalid - this constraint fails!
Unit string
// when set to true, specifies that the tolerance is a minimum check (rather than the default maximum check)
MinCheck bool
// when set to true, excludes the time when comparing
//
// Note: This also excludes the effect of any timezone offsets specified in either of the compared values
ExcTime bool
// when set to true, IgnoreNull makes the constraint less strict by ignoring null values
IgnoreNull bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
DatetimeTolerance constraint to check that a date/time (as an ISO string) value meets a tolerance against a specified value
Note: this constraint is strict - if the property value is not a valid ISO datetime then this constraint fails
func (*DatetimeTolerance) Check ¶
func (c *DatetimeTolerance) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*DatetimeTolerance) GetMessage ¶
func (c *DatetimeTolerance) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type DatetimeToleranceToNow ¶
type DatetimeToleranceToNow struct {
// the tolerance duration amount - which can be positive, negative or zero
//
// For negative values, this is the maximum duration into the past
//
// For positive values, this is the maximum duration into the future
//
// Note: If the value is zero then the behaviour is assumed to be "same" - but is then dependent on the unit
// specified. For example, if the Duration is zero and the Unit is specified as "year" then this constraint
// will check the same year
Duration int64
// is the string token specifying the unit in which the Duration is measured
//
// this can be "millennium", "century", "decade", "year", "month", "week", "day",
// "hour", "min", "sec" or "milli" (millisecond), "micro" (microsecond) or "nano" (nanosecond)
//
// Note: if this is empty, then "day" is assumed. If the token is invalid - this constraint fails!
Unit string
// when set to true, specifies that the tolerance is a minimum check (rather than the default maximum check)
MinCheck bool
// when set to true, excludes the time when comparing
//
// Note: This also excludes the effect of any timezone offsets specified in either of the compared values
ExcTime bool
// when set to true, IgnoreNull makes the constraint less strict by ignoring null values
IgnoreNull bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
DatetimeToleranceToNow constraint to check that a date/time (as an ISO string) value meets a tolerance against the current time
Note: this constraint is strict - if the property value is not a valid ISO datetime then this constraint fails
func (*DatetimeToleranceToNow) Check ¶
func (c *DatetimeToleranceToNow) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*DatetimeToleranceToNow) GetMessage ¶
func (c *DatetimeToleranceToNow) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type DatetimeToleranceToOther ¶
type DatetimeToleranceToOther struct {
// the property name of the other value to compare against
//
// Note: the PropertyName can also be JSON dot notation path - where leading dots allow traversal up
// the object tree and names, separated by dots, allow traversal down the object tree.
// A single dot at start is equivalent to no starting dot (i.e. a property name at the same level)
PropertyName string `v8n:"default"`
// the tolerance duration amount - which can be positive, negative or zero
//
// For negative values, this is the maximum duration into the past
//
// For positive values, this is the maximum duration into the future
//
// Note: If the value is zero then the behaviour is assumed to be "same" - but is then dependent on the unit
// specified. For example, if the Duration is zero and the Unit is specified as "year" then this constraint
// will check the same year
Duration int64
// is the string token specifying the unit in which the Duration is measured
//
// this can be "millennium", "century", "decade", "year", "month", "week", "day",
// "hour", "min", "sec" or "milli" (millisecond), "micro" (microsecond) or "nano" (nanosecond)
//
// Note: if this is empty, then "day" is assumed. If the token is invalid - this constraint fails!
Unit string
// when set to true, specifies that the tolerance is a minimum check (rather than the default maximum check)
MinCheck bool
// when set to true, excludes the time when comparing
//
// Note: This also excludes the effect of any timezone offsets specified in either of the compared values
ExcTime bool
// when set to true, IgnoreNull makes the constraint less strict by ignoring null values
//
// NB. ignoring nulls applies to both the property being checked and the other named property
IgnoreNull bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
DatetimeToleranceToOther constraint to check that a date/time (as an ISO string) value meets a tolerance against the value of another named property value
Note: this constraint is strict - if the property value is not a valid ISO datetime then this constraint fails
func (*DatetimeToleranceToOther) Check ¶
func (c *DatetimeToleranceToOther) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*DatetimeToleranceToOther) GetMessage ¶
func (c *DatetimeToleranceToOther) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type DatetimeYearsOld ¶
type DatetimeYearsOld struct {
// is the minimum age (not checked if this value is zero or less)
Minimum int
// is the maximum age (not checked if this value is zero or less)
Maximum int
// if set to true, ExclusiveMin specifies the minimum value is exclusive
ExclusiveMin bool
// if set to true, ExclusiveMax specifies the maximum value is exclusive
ExclusiveMax bool
// if set to true, only checks the minimum/maximum age against the current year - i.e. the current age is calculated
// based on 23:59:59.999999999 at 31st December of the current year
ThisYear bool
// is an optional string representing a threshold date at which the age is calculated
//
// If this is specified, the year part is ignored (the current year is always used)
//
// Note: if specified, this also overrides the ThisYear flag
ThresholdDate string
// if set, adjusts the way leapday birthdays are age calculated
//
// By default, leapday birthdays are taken as 1st March when the current year is not a leap year
//
// Setting LeapdayAdjust to true means that leapday birthdays are taken as 28th Feb
LeapdayAdjust bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string `v8n:"default"`
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
DatetimeYearsOld constraint checks that a date (datetime represented as string or time.Time) meets the specified minimum and/or maximum years-old. Can also be used to simply check a minimum age or maximum age
Notes:
* If the value being checked contains a time (hh:mm:ss), it is ignored (very few people know, or are expected to specify, their exact time of birth)
* If the value being checked is in the future - this constraint fails
* If both Minimum and Maximum are set to zero (or less) then no check is performed
func (*DatetimeYearsOld) Check ¶
func (c *DatetimeYearsOld) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*DatetimeYearsOld) GetMessage ¶
func (c *DatetimeYearsOld) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type DecoderProvider ¶
type DecoderProvider interface {
NewDecoder(r io.Reader, useNumber bool) *json.Decoder
NewDecoderFor(r io.Reader, validator *Validator) *json.Decoder
}
DecoderProvider is the interface needed for replacing the DefaultDecoderProvider
var DefaultDecoderProvider DecoderProvider = &defaultDecoderProvider{}
DefaultDecoderProvider is the decoder provider used by Validator - replace with your own if necessary
type Duration ¶
type Duration struct {
Negative bool
Years *float64
Months *float64
Weeks *float64
Days *float64
Hours *float64
Minutes *float64
Seconds *float64
}
Duration represents a parsed ISO8601 duration
func ParseDuration ¶
type EqualsOther ¶
type EqualsOther struct {
// the property name of the other value to compare against
//
// Note: the PropertyName can also be JSON dot notation path - where leading dots allow traversal up
// the object tree and names, separated by dots, allow traversal down the object tree.
// A single dot at start is equivalent to no starting dot (i.e. a property name at the same level)
PropertyName string `v8n:"default"`
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
EqualsOther constraint to check that a property value equals the value of another named property
func (*EqualsOther) Check ¶
func (c *EqualsOther) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*EqualsOther) GetMessage ¶
func (c *EqualsOther) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type FailWhen ¶
type FailWhen struct {
// the conditions under which to fail
Conditions []string `v8n:"default"`
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, StopAll stops the entire validation
StopAll bool
}
FailWhen is a utility constraint that fails when specified conditions are met
func (*FailWhen) Check ¶
func (c *FailWhen) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*FailWhen) GetMessage ¶
func (c *FailWhen) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type FailWith ¶
type FailWith struct {
// Others is the others expression to be evaluated to determine whether the constraint should fail
Others OthersExpr `v8n:"default"`
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, StopAll stops the entire validation
StopAll bool
}
FailWith is a utility constraint that fails when specified others property expression evaluates to true
func (*FailWith) Check ¶
func (c *FailWith) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*FailWith) GetMessage ¶
func (c *FailWith) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type FailingConstraint ¶
type FailingConstraint struct {
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string `v8n:"default"`
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, StopAll stops the entire validation
StopAll bool
}
FailingConstraint is a utility constraint that always fails
func (*FailingConstraint) Check ¶
func (c *FailingConstraint) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*FailingConstraint) GetMessage ¶
func (c *FailingConstraint) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type GreaterThan ¶
type GreaterThan struct {
// the value to compare against
Value float64 `v8n:"default"`
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
GreaterThan constraint to check that a numeric value is greater than a specified value
Note: This constraint is stricter than Minimum, Maximum and Range constraints in that if the property value is not a numeric then this constraint fails
func (*GreaterThan) Check ¶
func (c *GreaterThan) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*GreaterThan) GetMessage ¶
func (c *GreaterThan) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type GreaterThanOrEqual ¶
type GreaterThanOrEqual struct {
// the value to compare against
Value float64 `v8n:"default"`
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
GreaterThanOrEqual constraint to check that a numeric value is greater than or equal to a specified value
Note: This constraint is stricter than Minimum, Maximum and Range constraints in that if the property value is not a numeric then this constraint fails
func (*GreaterThanOrEqual) Check ¶
func (c *GreaterThanOrEqual) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*GreaterThanOrEqual) GetMessage ¶
func (c *GreaterThanOrEqual) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type GreaterThanOrEqualOther ¶
type GreaterThanOrEqualOther struct {
// the property name of the other value to compare against
//
// Note: the PropertyName can also be JSON dot notation path - where leading dots allow traversal up
// the object tree and names, separated by dots, allow traversal down the object tree.
// A single dot at start is equivalent to no starting dot (i.e. a property name at the same level)
PropertyName string `v8n:"default"`
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
GreaterThanOrEqualOther constraint to check that a numeric value is greater than or equal to another named property value
Note: this constraint is strict - if either the current or other property is not numeric then this constraint fails
func (*GreaterThanOrEqualOther) Check ¶
func (c *GreaterThanOrEqualOther) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*GreaterThanOrEqualOther) GetMessage ¶
func (c *GreaterThanOrEqualOther) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type GreaterThanOther ¶
type GreaterThanOther struct {
// the property name of the other value to compare against
//
// Note: the PropertyName can also be JSON dot notation path - where leading dots allow traversal up
// the object tree and names, separated by dots, allow traversal down the object tree.
// A single dot at start is equivalent to no starting dot (i.e. a property name at the same level)
PropertyName string `v8n:"default"`
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
GreaterThanOther constraint to check that a numeric value is greater than another named property value
Note: this constraint is strict - if either the current or other property is not numeric then this constraint fails
func (*GreaterThanOther) Check ¶
func (c *GreaterThanOther) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*GreaterThanOther) GetMessage ¶
func (c *GreaterThanOther) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type I18n ¶
type I18n interface {
ContextFromRequest(r *http.Request) I18nContext
DefaultContext() I18nContext
}
I18n interface for supporting i18n (internationalisation) in valix - used to provide I18nContext interfaces upon request by the Validators
var (
DefaultI18nProvider I18n = &defaultI18nProvider{}
)
type I18nContext ¶
type I18nContext interface {
TranslateMessage(msg string) string
TranslateFormat(format string, a ...interface{}) string
TranslateToken(token string) string
Language() string
Region() string
}
I18nContext is the interface passed around during validation that provides translations of messages, message formats and individual word tokens
type IsNotNull ¶
type IsNotNull struct {
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string `v8n:"default"`
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
IsNotNull is a utility constraint to check that a value is not null
Normally, null checking would be performed by the PropertyValidator.NotNull setting - however, it may be the case that null is only disallowed under certain conditions
func (*IsNotNull) Check ¶
func (c *IsNotNull) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements the Constraint.Check and checks the constraints within the set
func (*IsNotNull) GetMessage ¶
func (c *IsNotNull) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type IsNull ¶
type IsNull struct {
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string `v8n:"default"`
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
IsNull is a utility constraint to check that a value is null
Normally, null checking would be performed by the PropertyValidator.NotNull setting - however, it may be the case that, under certain conditions, null is the required value
func (*IsNull) Check ¶
func (c *IsNull) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements the Constraint.Check and checks the constraints within the set
func (*IsNull) GetMessage ¶
func (c *IsNull) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type JsonType ¶
type JsonType int
JsonType is the type for JSON values
const ( // JsonAny matches any JSON value type JsonAny JsonType = iota // JsonString checks JSON value type is a string JsonString // JsonDatetime checks JSON value type is a string and is a valid parseable datetime JsonDatetime // JsonNumber checks JSON value type is a number JsonNumber // JsonInteger checks JSON value type is a number (that is or can be expressed as an int) JsonInteger // JsonBoolean checks JSON value type is a boolean JsonBoolean // JsonObject checks JSON value type is an object JsonObject // JsonArray checks JSON value type is an array JsonArray )
func JsonTypeFromString ¶
func (*JsonType) UnmarshalJSON ¶
type Length ¶
type Length struct {
// the minimum length
Minimum int
// the maximum length (only checked if this value is > 0)
Maximum int
// if set to true, ExclusiveMin specifies the minimum value is exclusive
ExclusiveMin bool
// if set to true, ExclusiveMax specifies the maximum value is exclusive
ExclusiveMax bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
Length constraint to check that a property value has minimum and maximum length
This constraint can be used for object, array and string property values - however, if checking string lengths it is better to use the StringLength constraint
* when checking array values, the number of elements in the array is checked
* when checking object values, the number of properties in the object is checked
* when checking string values, the length of the string is checked
func (*Length) Check ¶
func (c *Length) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*Length) GetMessage ¶
func (c *Length) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type LengthExact ¶
type LengthExact struct {
// the length to check
Value int `v8n:"default"`
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
LengthExact constraint to check that a property value has a specific length
This constraint can be used for object, array and string property values - however, if checking string lengths it is better to use the StringExactLength constraint
* when checking array values, the number of elements in the array is checked
* when checking object values, the number of properties in the object is checked
* when checking string values, the length of the string is checked
func (*LengthExact) Check ¶
func (c *LengthExact) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*LengthExact) GetMessage ¶
func (c *LengthExact) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type LessThan ¶
type LessThan struct {
// the value to compare against
Value float64 `v8n:"default"`
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
LessThan constraint to check that a numeric value is less than a specified value
Note: This constraint is stricter than Minimum, Maximum and Range constraints in that if the property value is not a numeric then this constraint fails
func (*LessThan) Check ¶
func (c *LessThan) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*LessThan) GetMessage ¶
func (c *LessThan) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type LessThanOrEqual ¶
type LessThanOrEqual struct {
// the value to compare against
Value float64 `v8n:"default"`
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
LessThanOrEqual constraint to check that a numeric value is less than or equal to a specified value
Note: This constraint is stricter than Minimum, Maximum and Range constraints in that if the property value is not a numeric then this constraint fails
func (*LessThanOrEqual) Check ¶
func (c *LessThanOrEqual) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*LessThanOrEqual) GetMessage ¶
func (c *LessThanOrEqual) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type LessThanOrEqualOther ¶
type LessThanOrEqualOther struct {
// the property name of the other value to compare against
//
// Note: the PropertyName can also be JSON dot notation path - where leading dots allow traversal up
// the object tree and names, separated by dots, allow traversal down the object tree.
// A single dot at start is equivalent to no starting dot (i.e. a property name at the same level)
PropertyName string `v8n:"default"`
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
LessThanOrEqualOther constraint to check that a numeric value is less than or equal to another named property value
Note: this constraint is strict - if either the current or other property is not numeric then this constraint fails
func (*LessThanOrEqualOther) Check ¶
func (c *LessThanOrEqualOther) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*LessThanOrEqualOther) GetMessage ¶
func (c *LessThanOrEqualOther) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type LessThanOther ¶
type LessThanOther struct {
// the property name of the other value to compare against
//
// Note: the PropertyName can also be JSON dot notation path - where leading dots allow traversal up
// the object tree and names, separated by dots, allow traversal down the object tree.
// A single dot at start is equivalent to no starting dot (i.e. a property name at the same level)
PropertyName string `v8n:"default"`
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
LessThanOther constraint to check that a numeric value is less than another named property value
Note: this constraint is strict - if either the current or other property is not numeric then this constraint fails
func (*LessThanOther) Check ¶
func (c *LessThanOther) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*LessThanOther) GetMessage ¶
func (c *LessThanOther) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type Maximum ¶
type Maximum struct {
// the maximum value
Value float64 `v8n:"default"`
// if set to true, ExclusiveMax specifies the maximum value is exclusive
ExclusiveMax bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
Maximum constraint to check that a numeric value is less than or equal to a specified maximum
func (*Maximum) Check ¶
func (c *Maximum) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*Maximum) GetMessage ¶
func (c *Maximum) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type MaximumInt ¶
type MaximumInt struct {
// the maximum value
Value int64 `v8n:"default"`
// if set to true, ExclusiveMax specifies the maximum value is exclusive
ExclusiveMax bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
MaximumInt constraint to check that an integer value is less than or equal to a specified maximum
func (*MaximumInt) Check ¶
func (c *MaximumInt) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*MaximumInt) GetMessage ¶
func (c *MaximumInt) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type Minimum ¶
type Minimum struct {
// the minimum value
Value float64 `v8n:"default"`
// if set to true, ExclusiveMin specifies the minimum value is exclusive
ExclusiveMin bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
Minimum constraint to check that a numeric value is greater than or equal to a specified minimum
func (*Minimum) Check ¶
func (c *Minimum) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*Minimum) GetMessage ¶
func (c *Minimum) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type MinimumInt ¶
type MinimumInt struct {
// the minimum value
Value int64 `v8n:"default"`
// if set to true, ExclusiveMin specifies the minimum value is exclusive
ExclusiveMin bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
MinimumInt constraint to check that an integer numeric value is greater than or equal to a specified minimum
func (*MinimumInt) Check ¶
func (c *MinimumInt) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*MinimumInt) GetMessage ¶
func (c *MinimumInt) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type MultipleOf ¶
type MultipleOf struct {
// the multiple of value to check
Value int64 `v8n:"default"`
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
MultipleOf constraint to check that an integer value is a multiple of a specific number
Note: this constraint will check values that are float or json Number - but the check will fail if either of these is not a 'whole number'
func (*MultipleOf) Check ¶
func (c *MultipleOf) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*MultipleOf) GetMessage ¶
func (c *MultipleOf) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type Negative ¶
type Negative struct {
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string `v8n:"default"`
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
Negative constraint to check that a numeric value is negative
func (*Negative) Check ¶
func (c *Negative) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*Negative) GetMessage ¶
func (c *Negative) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type NegativeOrZero ¶
type NegativeOrZero struct {
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string `v8n:"default"`
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
NegativeOrZero constraint to check that a numeric value is negative or zero
func (*NegativeOrZero) Check ¶
func (c *NegativeOrZero) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*NegativeOrZero) GetMessage ¶
func (c *NegativeOrZero) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type NetIsCIDR ¶
type NetIsCIDR struct {
// if set, allows only CIDR v4
V4Only bool
// if set, allows only CIDR v6
V6Only bool
// if set, disallows loopback addresses
DisallowLoopback bool
// if set, disallows private addresses
DisallowPrivate bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string `v8n:"default"`
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
NetIsCIDR constraint to check that string value is a valid CIDR (v4 or v6) address
NB. Setting both V4Only and V6Only to true will cause this constraint to always fail!
func (*NetIsCIDR) Check ¶
func (c *NetIsCIDR) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*NetIsCIDR) GetMessage ¶
func (c *NetIsCIDR) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type NetIsHostname ¶
type NetIsHostname struct {
// CheckHost when set, checks the host (using net.LookupHost)
CheckHost bool
// AllowIPAddress when set, allows IP address hostnames
AllowIPAddress bool
// AllowIPV6 when set, allows IP v6 address hostnames
AllowIPV6 bool
// AllowLocal when set, allows hostnames 'local' (e.g. "localhost", "local", "localdomain", "127.0.0.1", "::1")
AllowLocal bool
// AllowTldOnly when set, allows hostnames with only Tld specified (e.g. "audi")
AllowTldOnly bool
// AllowGeographicTlds when set, allows hostnames with geographic Tlds (e.g. "some-company.africa")
AllowGeographicTlds bool
// AllowGenericTlds when set, allows hostnames with generic Tlds (e.g. "some.academy")
AllowGenericTlds bool
// AllowBrandTlds when set, allows hostnames with brand Tlds (e.g. "my.audi")
AllowBrandTlds bool
// AllowInfraTlds when set, allows hostnames with infrastructure Tlds (e.g. "arpa")
AllowInfraTlds bool
// AllowTestTlds when set, allows hostnames with test Tlds and test domains (e.g. "example.com", "test.com")
AllowTestTlds bool
// AddCountryCodeTlds is an optional slice of additional country (and geographic) Tlds to allow
AddCountryCodeTlds []string
// ExcCountryCodeTlds is an optional slice of country (and geographic) Tlds to disallow
ExcCountryCodeTlds []string
// AddGenericTlds is an optional slice of additional generic Tlds to allow (only checked if AllowGenericTlds is also set)
AddGenericTlds []string
// ExcGenericTlds is an optional slice of generic Tlds to disallow (only relevant if AllowGenericTlds is also set)
ExcGenericTlds []string
// AddBrandTlds is an optional slice of additional brand Tlds to allow (only checked if AllowBrandTlds is also set)
AddBrandTlds []string
// ExcBrandTlds is an optional slice of brand Tlds to disallow (only relevant if AllowBrandTlds is also set)
ExcBrandTlds []string
// AddLocalTlds is an optional slice of additional local Tlds to allow (only checked if AllowLocal is also set)
AddLocalTlds []string
// ExcLocalTlds is an optional slice of local Tlds to disallow (only relevant if AllowLocal is also set)
ExcLocalTlds []string
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
NetIsHostname constraint to check that string value is a valid hostname
func (*NetIsHostname) Check ¶
func (c *NetIsHostname) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*NetIsHostname) GetMessage ¶
func (c *NetIsHostname) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type NetIsIP ¶
type NetIsIP struct {
// if set, allows only IP v4
V4Only bool
// if set, allows only IP v6
V6Only bool
// if set, checks that the address is resolvable
Resolvable bool
// if set, disallows loopback addresses
DisallowLoopback bool
// if set, disallows private addresses
DisallowPrivate bool
// if set, allows value of "localhost" to be seen as valid
AllowLocalhost bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string `v8n:"default"`
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
NetIsIP constraint to check that string value is a valid IP (v4 or v6) address
NB. Setting both V4Only and V6Only to true will cause this constraint to always fail!
func (*NetIsIP) Check ¶
func (c *NetIsIP) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*NetIsIP) GetMessage ¶
func (c *NetIsIP) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type NetIsMac ¶
type NetIsMac struct {
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string `v8n:"default"`
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
NetIsMac constraint to check that string value is a valid MAC address
func (*NetIsMac) Check ¶
func (c *NetIsMac) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*NetIsMac) GetMessage ¶
func (c *NetIsMac) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type NetIsTCP ¶
type NetIsTCP struct {
// if set, allows only TCP v4
V4Only bool
// if set, allows only TCP v6
V6Only bool
// if set, disallows loopback addresses
DisallowLoopback bool
// if set, disallows private addresses
DisallowPrivate bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string `v8n:"default"`
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
NetIsTCP constraint to check that string value is a valid resolvable TCP (v4 or v6) address
NB. Setting both V4Only and V6Only to true will cause this constraint to always fail!
func (*NetIsTCP) Check ¶
func (c *NetIsTCP) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*NetIsTCP) GetMessage ¶
func (c *NetIsTCP) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type NetIsTld ¶
type NetIsTld struct {
AllowGeographicTlds bool
AllowGenericTlds bool
AllowBrandTlds bool
AddCountryCodeTlds []string
ExcCountryCodeTlds []string
AddGenericTlds []string
ExcGenericTlds []string
AddBrandTlds []string
ExcBrandTlds []string
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string `v8n:"default"`
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
NetIsTld constraint to check that string value is a valid Tld (top level domain)
func (*NetIsTld) Check ¶
func (c *NetIsTld) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*NetIsTld) GetMessage ¶
func (c *NetIsTld) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type NetIsUDP ¶
type NetIsUDP struct {
// if set, allows only TCP v4
V4Only bool
// if set, allows only TCP v6
V6Only bool
// if set, disallows loopback addresses
DisallowLoopback bool
// if set, disallows private addresses
DisallowPrivate bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string `v8n:"default"`
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
NetIsUDP constraint to check that string value is a valid resolvable UDP (v4 or v6) address
NB. Setting both V4Only and V6Only to true will cause this constraint to always fail!
func (*NetIsUDP) Check ¶
func (c *NetIsUDP) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*NetIsUDP) GetMessage ¶
func (c *NetIsUDP) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type NetIsURI ¶
type NetIsURI struct {
// if set, the host is also checked (see also AllowIPAddress and others)
CheckHost bool `v8n:"default"`
// AllowIPAddress when set, allows IP address hostnames
AllowIPAddress bool
// AllowIPV6 when set, allows IP v6 address hostnames
AllowIPV6 bool
// AllowLocal when set, allows hostnames 'local' (e.g. "localhost", "local", "localdomain", "127.0.0.1", "::1")
AllowLocal bool
// AllowTldOnly when set, allows hostnames with only Tld specified (e.g. "audi")
AllowTldOnly bool
// AllowGeographicTlds when set, allows hostnames with geographic Tlds (e.g. "some-company.africa")
AllowGeographicTlds bool
// AllowGenericTlds when set, allows hostnames with generic Tlds (e.g. "some.academy")
AllowGenericTlds bool
// AllowBrandTlds when set, allows hostnames with brand Tlds (e.g. "my.audi")
AllowBrandTlds bool
// AllowInfraTlds when set, allows hostnames with infrastructure Tlds (e.g. "arpa")
AllowInfraTlds bool
// AllowTestTlds when set, allows hostnames with test Tlds and test domains (e.g. "example.com", "test.com")
AllowTestTlds bool
// AddCountryCodeTlds is an optional slice of additional country (and geographic) Tlds to allow
AddCountryCodeTlds []string
// ExcCountryCodeTlds is an optional slice of country (and geographic) Tlds to disallow
ExcCountryCodeTlds []string
// AddGenericTlds is an optional slice of additional generic Tlds to allow (only checked if AllowGenericTlds is also set)
AddGenericTlds []string
// ExcGenericTlds is an optional slice of generic Tlds to disallow (only relevant if AllowGenericTlds is also set)
ExcGenericTlds []string
// AddBrandTlds is an optional slice of additional brand Tlds to allow (only checked if AllowBrandTlds is also set)
AddBrandTlds []string
// ExcBrandTlds is an optional slice of brand Tlds to disallow (only relevant if AllowBrandTlds is also set)
ExcBrandTlds []string
// AddLocalTlds is an optional slice of additional local Tlds to allow (only checked if AllowLocal is also set)
AddLocalTlds []string
// ExcLocalTlds is an optional slice of local Tlds to disallow (only relevant if AllowLocal is also set)
ExcLocalTlds []string
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
NetIsURI constraint to check that string value is a valid URI
func (*NetIsURI) Check ¶
func (c *NetIsURI) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*NetIsURI) GetMessage ¶
func (c *NetIsURI) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type NetIsURL ¶
type NetIsURL struct {
// if set, the host is also checked (see also AllowIPAddress and others)
CheckHost bool `v8n:"default"`
// AllowIPAddress when set, allows IP address hostnames
AllowIPAddress bool
// AllowIPV6 when set, allows IP v6 address hostnames
AllowIPV6 bool
// AllowLocal when set, allows hostnames 'local' (e.g. "localhost", "local", "localdomain", "127.0.0.1", "::1")
AllowLocal bool
// AllowTldOnly when set, allows hostnames with only Tld specified (e.g. "audi")
AllowTldOnly bool
// AllowGeographicTlds when set, allows hostnames with geographic Tlds (e.g. "some-company.africa")
AllowGeographicTlds bool
// AllowGenericTlds when set, allows hostnames with generic Tlds (e.g. "some.academy")
AllowGenericTlds bool
// AllowBrandTlds when set, allows hostnames with brand Tlds (e.g. "my.audi")
AllowBrandTlds bool
// AllowInfraTlds when set, allows hostnames with infrastructure Tlds (e.g. "arpa")
AllowInfraTlds bool
// AllowTestTlds when set, allows hostnames with test Tlds and test domains (e.g. "example.com", "test.com")
AllowTestTlds bool
// AddCountryCodeTlds is an optional slice of additional country (and geographic) Tlds to allow
AddCountryCodeTlds []string
// ExcCountryCodeTlds is an optional slice of country (and geographic) Tlds to disallow
ExcCountryCodeTlds []string
// AddGenericTlds is an optional slice of additional generic Tlds to allow (only checked if AllowGenericTlds is also set)
AddGenericTlds []string
// ExcGenericTlds is an optional slice of generic Tlds to disallow (only relevant if AllowGenericTlds is also set)
ExcGenericTlds []string
// AddBrandTlds is an optional slice of additional brand Tlds to allow (only checked if AllowBrandTlds is also set)
AddBrandTlds []string
// ExcBrandTlds is an optional slice of brand Tlds to disallow (only relevant if AllowBrandTlds is also set)
ExcBrandTlds []string
// AddLocalTlds is an optional slice of additional local Tlds to allow (only checked if AllowLocal is also set)
AddLocalTlds []string
// ExcLocalTlds is an optional slice of local Tlds to disallow (only relevant if AllowLocal is also set)
ExcLocalTlds []string
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
NetIsURL constraint to check that string value is a valid URL
func (*NetIsURL) Check ¶
func (c *NetIsURL) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*NetIsURL) GetMessage ¶
func (c *NetIsURL) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type NotEmpty ¶
type NotEmpty struct {
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
NotEmpty constraint to check that a map or slice property value is not empty (has properties or array elements)
Note: can also be used with string properties (and will check the string is not empty - same as StringNotEmpty)
func (*NotEmpty) Check ¶
func (c *NotEmpty) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*NotEmpty) GetMessage ¶
func (c *NotEmpty) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type NotEqualsOther ¶
type NotEqualsOther struct {
// the property name of the other value to compare against
//
// Note: the PropertyName can also be JSON dot notation path - where leading dots allow traversal up
// the object tree and names, separated by dots, allow traversal down the object tree.
// A single dot at start is equivalent to no starting dot (i.e. a property name at the same level)
PropertyName string `v8n:"default"`
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the other property is not present (even though the not equals would technically be ok)
Strict bool
}
NotEqualsOther constraint to check that a property value not equals the value of another named property
func (*NotEqualsOther) Check ¶
func (c *NotEqualsOther) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*NotEqualsOther) GetMessage ¶
func (c *NotEqualsOther) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type OasInfo ¶
type OasInfo struct {
Description string
Title string
Format string
Example string
Deprecated bool
}
OasInfo is OAS (Open API Spec) information about an validator or property validator
type Option ¶
var ( // OptionIgnoreOasTags option for ValidatorFor - ignores oas tags on struct fields OptionIgnoreOasTags Option = _OptionIgnoreOasTags // OptionConstraints option for ValidatorFor - adds constraints to the Validator OptionConstraints = _OptionConstraints // OptionIgnoreUnknownProperties option for ValidatorFor - sets Validator to ignore unknown properties OptionIgnoreUnknownProperties Option = _OptionIgnoreUnknownProperties // OptionDisallowUnknownProperties option for ValidatorFor - sets Validator to not ignore unknown properties OptionDisallowUnknownProperties Option = _OptionDisallowUnknownProperties // OptionAllowNullJson option for ValidatorFor - sets Validator to allow JSON null OptionAllowNullJson Option = _OptionAllowNullJson // OptionDisallowNullJson option for ValidatorFor - sets Validator to not allow JSON null OptionDisallowNullJson Option = _OptionDisallowNullJson // OptionAllowArray option for ValidatorFor - sets Validator to allow JSON array OptionAllowArray Option = _OptionAllowArray // OptionDisallowArray option for ValidatorFor - sets Validator to not allow JSON array OptionDisallowArray Option = _OptionDisallowArray // OptionAllowObject option for ValidatorFor - sets Validator to allow JSON object OptionAllowObject Option = _OptionAllowObject // OptionDisallowObject option for ValidatorFor - sets Validator to not allow JSON object OptionDisallowObject Option = _OptionDisallowObject // OptionStopOnFirst option for ValidatorFor - sets Validator to stop on first violation OptionStopOnFirst Option = _OptionStopOnFirst // OptionDontStopOnFirst option for ValidatorFor - sets Validator to not stop on first violation OptionDontStopOnFirst Option = _OptionDontStopOnFirst // OptionOrderedPropertyChecks option for ValidatorFor - sets Validator to do ordered property checks OptionOrderedPropertyChecks Option = _OptionOrderedPropertyChecks // OptionUnOrderedPropertyChecks option for ValidatorFor - sets Validator to not do ordered property checks // Note that if the validator has any properties with a non-zero order, ordered property checks are always carried out OptionUnOrderedPropertyChecks Option = _OptionUnOrderedPropertyChecks )
type Other ¶
type Other interface {
// Evaluate evaluates the presence or non-presence of named properties in a given object
//
// the currentObj arg is the object that the property should be checked for within
//
// the ancestryValues arg provides the ancestry of objects in case there is a need to traverse
// upwards. The first, index 0, item in the ancestryValues slice will be the parent of the
// currentObj... the second item will be the grandparent of currentObj... etc.
Evaluate(currentObj map[string]interface{}, ancestryValues []interface{}, vcx *ValidatorContext) bool
// GetOperator returns the boolean operator (And / Or)
GetOperator() BooleanOperator
// String method provides a string representation of the expression
String() string
}
Other is the interface for items in OthersExpr - and is implemented by OtherProperty, OtherGrouping and by OthersExpr itself
type OtherGrouping ¶
type OtherGrouping struct {
// Of is the items within the grouping
Of OthersExpr
// Not is whether the grouping is NOTed (!)
Not bool
// Op is the boolean operator (And / Or) applied to the previous resultant
Op BooleanOperator
}
func NewOtherGrouping ¶
func NewOtherGrouping(items ...interface{}) *OtherGrouping
func (*OtherGrouping) ANDed ¶
func (g *OtherGrouping) ANDed() *OtherGrouping
func (*OtherGrouping) AddAndGroup ¶
func (g *OtherGrouping) AddAndGroup(of *OthersExpr) *OtherGrouping
func (*OtherGrouping) AddAndNotGroup ¶
func (g *OtherGrouping) AddAndNotGroup(of *OthersExpr) *OtherGrouping
func (*OtherGrouping) AddAndNotProperty ¶
func (g *OtherGrouping) AddAndNotProperty(name string) *OtherGrouping
func (*OtherGrouping) AddAndProperty ¶
func (g *OtherGrouping) AddAndProperty(name string) *OtherGrouping
func (*OtherGrouping) AddGroup ¶
func (g *OtherGrouping) AddGroup(of *OthersExpr) *OtherGrouping
func (*OtherGrouping) AddNotGroup ¶
func (g *OtherGrouping) AddNotGroup(of *OthersExpr) *OtherGrouping
func (*OtherGrouping) AddNotProperty ¶
func (g *OtherGrouping) AddNotProperty(name string) *OtherGrouping
func (*OtherGrouping) AddOrGroup ¶
func (g *OtherGrouping) AddOrGroup(of *OthersExpr) *OtherGrouping
func (*OtherGrouping) AddOrNotGroup ¶
func (g *OtherGrouping) AddOrNotGroup(of *OthersExpr) *OtherGrouping
func (*OtherGrouping) AddOrNotProperty ¶
func (g *OtherGrouping) AddOrNotProperty(name string) *OtherGrouping
func (*OtherGrouping) AddOrProperty ¶
func (g *OtherGrouping) AddOrProperty(name string) *OtherGrouping
func (*OtherGrouping) AddProperty ¶
func (g *OtherGrouping) AddProperty(name string) *OtherGrouping
func (*OtherGrouping) AddXorGroup ¶
func (g *OtherGrouping) AddXorGroup(of *OthersExpr) *OtherGrouping
func (*OtherGrouping) AddXorNotGroup ¶
func (g *OtherGrouping) AddXorNotGroup(of *OthersExpr) *OtherGrouping
func (*OtherGrouping) AddXorNotProperty ¶
func (g *OtherGrouping) AddXorNotProperty(name string) *OtherGrouping
func (*OtherGrouping) AddXorProperty ¶
func (g *OtherGrouping) AddXorProperty(name string) *OtherGrouping
func (*OtherGrouping) Evaluate ¶
func (g *OtherGrouping) Evaluate(currentObj map[string]interface{}, ancestryValues []interface{}, vcx *ValidatorContext) bool
Evaluate implements Other.Evaluate
func (*OtherGrouping) GetOperator ¶
func (g *OtherGrouping) GetOperator() BooleanOperator
GetOperator implements Other.GetOperator (always returns And)
func (*OtherGrouping) NOTed ¶
func (g *OtherGrouping) NOTed() *OtherGrouping
func (*OtherGrouping) ORed ¶
func (g *OtherGrouping) ORed() *OtherGrouping
func (*OtherGrouping) String ¶
func (g *OtherGrouping) String() string
func (*OtherGrouping) XORed ¶
func (g *OtherGrouping) XORed() *OtherGrouping
type OtherProperty ¶
type OtherProperty struct {
// Name is the name of the property whose presence or non-presence is to be checked
Name string
// Not is whether presence is NOTed (!) - i.e. if Not is set to true, then the non-presence is checked
Not bool
// Op is the boolean operator (And / Or) applied to the previous resultant
Op BooleanOperator
// contains filtered or unexported fields
}
func NewOtherProperty ¶
func NewOtherProperty(name string) *OtherProperty
func (*OtherProperty) ANDed ¶
func (p *OtherProperty) ANDed() *OtherProperty
func (*OtherProperty) Evaluate ¶
func (p *OtherProperty) Evaluate(currentObj map[string]interface{}, ancestryValues []interface{}, vcx *ValidatorContext) bool
Evaluate implements Other.Evaluate
func (*OtherProperty) GetOperator ¶
func (p *OtherProperty) GetOperator() BooleanOperator
GetOperator implements Other.GetOperator
func (*OtherProperty) NOTed ¶
func (p *OtherProperty) NOTed() *OtherProperty
func (*OtherProperty) ORed ¶
func (p *OtherProperty) ORed() *OtherProperty
func (*OtherProperty) String ¶
func (p *OtherProperty) String() string
func (*OtherProperty) XORed ¶
func (p *OtherProperty) XORed() *OtherProperty
type OthersExpr ¶
type OthersExpr []Other
OthersExpr is a list of expressions (OtherProperty, OtherGrouping) that can be evaluated against an object to determine the presence or non-presence of specific named properties
This is used by the PropertyValidator.RequiredWith and PropertyValidator.UnwantedWith fields
func MustParseExpression ¶
func MustParseExpression(expr string) OthersExpr
MustParseExpression is the same as ParseExpression - but panics if there is an error
func ParseExpression ¶
func ParseExpression(expr string) (OthersExpr, error)
ParseExpression parses a string expression representing the presence or non-presence of named properties in an object
An example:
expr, err := valix.ParseExpression(`(foo && bar) || (foo && baz) || (bar && baz) && !(foo && bar && baz)`)
func (*OthersExpr) AddAndGroup ¶
func (o *OthersExpr) AddAndGroup(of *OthersExpr) *OthersExpr
func (*OthersExpr) AddAndNotGroup ¶
func (o *OthersExpr) AddAndNotGroup(of *OthersExpr) *OthersExpr
func (*OthersExpr) AddAndNotProperty ¶
func (o *OthersExpr) AddAndNotProperty(name string) *OthersExpr
func (*OthersExpr) AddAndProperty ¶
func (o *OthersExpr) AddAndProperty(name string) *OthersExpr
func (*OthersExpr) AddGroup ¶
func (o *OthersExpr) AddGroup(of *OthersExpr) *OthersExpr
func (*OthersExpr) AddNotGroup ¶
func (o *OthersExpr) AddNotGroup(of *OthersExpr) *OthersExpr
func (*OthersExpr) AddNotProperty ¶
func (o *OthersExpr) AddNotProperty(name string) *OthersExpr
func (*OthersExpr) AddOrGroup ¶
func (o *OthersExpr) AddOrGroup(of *OthersExpr) *OthersExpr
func (*OthersExpr) AddOrNotGroup ¶
func (o *OthersExpr) AddOrNotGroup(of *OthersExpr) *OthersExpr
func (*OthersExpr) AddOrNotProperty ¶
func (o *OthersExpr) AddOrNotProperty(name string) *OthersExpr
func (*OthersExpr) AddOrProperty ¶
func (o *OthersExpr) AddOrProperty(name string) *OthersExpr
func (*OthersExpr) AddProperty ¶
func (o *OthersExpr) AddProperty(name string) *OthersExpr
func (*OthersExpr) AddXorGroup ¶
func (o *OthersExpr) AddXorGroup(of *OthersExpr) *OthersExpr
func (*OthersExpr) AddXorNotGroup ¶
func (o *OthersExpr) AddXorNotGroup(of *OthersExpr) *OthersExpr
func (*OthersExpr) AddXorNotProperty ¶
func (o *OthersExpr) AddXorNotProperty(name string) *OthersExpr
func (*OthersExpr) AddXorProperty ¶
func (o *OthersExpr) AddXorProperty(name string) *OthersExpr
func (OthersExpr) Clone ¶
func (src OthersExpr) Clone() OthersExpr
func (*OthersExpr) Evaluate ¶
func (o *OthersExpr) Evaluate(currentObj map[string]interface{}, ancestryValues []interface{}, vcx *ValidatorContext) bool
Evaluate implements Other.Evaluate
func (*OthersExpr) GetOperator ¶
func (o *OthersExpr) GetOperator() BooleanOperator
GetOperator implements Other.GetOperator (always returns And)
func (*OthersExpr) MarshalJSON ¶
func (o *OthersExpr) MarshalJSON() ([]byte, error)
func (*OthersExpr) String ¶
func (o *OthersExpr) String() string
func (*OthersExpr) UnmarshalJSON ¶
func (o *OthersExpr) UnmarshalJSON(data []byte) error
type Positive ¶
type Positive struct {
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string `v8n:"default"`
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
Positive constraint to check that a numeric value is positive (exc. zero)
func (*Positive) Check ¶
func (c *Positive) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*Positive) GetMessage ¶
func (c *Positive) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type PositiveOrZero ¶
type PositiveOrZero struct {
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string `v8n:"default"`
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
PositiveOrZero constraint to check that a numeric value is positive or zero
func (*PositiveOrZero) Check ¶
func (c *PositiveOrZero) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*PositiveOrZero) GetMessage ¶
func (c *PositiveOrZero) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type PostPatternChecker ¶
type Preset ¶
type Preset interface {
Check(v string) bool
GetRegexp() *regexp.Regexp
GetPostChecker() PostPatternChecker
GetMessage() string
}
Preset is the interface used for presets (any preset registered directly using RegisterPreset must implement this interface)
func GetRegisteredPreset ¶
type Properties ¶
type Properties map[string]*PropertyValidator
Properties type used by Validator.Properties
func (Properties) Clone ¶
func (src Properties) Clone() Properties
type PropertyNameProvider ¶
type PropertyNameProvider interface {
// NameFor provides the property name for a given struct field (return ok false if default field name is to be used)
NameFor(field reflect.StructField) (name string, ok bool)
}
var DefaultPropertyNameProvider PropertyNameProvider = &defaultPropertyNameProvider{}
DefaultPropertyNameProvider is the property name provider used by Validator - replace with your own if necessary
type PropertyValidator ¶
type PropertyValidator struct {
// Type specifies the property type to be checked (i.e. one of Type)
//
// If this value is not one of Type (or an empty string), then the property type is not checked
Type JsonType
// NotNull specifies that the value of the property may not be null
NotNull bool
// Mandatory specifies that the property must be present
Mandatory bool
// MandatoryWhen is complimentary to the Mandatory property - and limits the conditions under which the property is
// seen as mandatory (if this is empty and Mandatory is set - then the property is always mandatory)
//
// Note: If the Mandatory property is not set to true - this property has no effect!
MandatoryWhen Conditions
// Constraints is a slice of Constraint items and are checked in the order they are specified
Constraints Constraints
// ObjectValidator is checked, if specified, after all Constraints are checked
ObjectValidator *Validator
// Order is the order in which the property is checked (see Validator.OrderedPropertyChecks)
//
// Note: setting any property with Order other than 0 (zero) will force the validator to use ordered property checks
// (i.e. as if Validator.OrderedPropertyChecks had been set to true)
Order int
// StopOnFirst if set, instructs the property validator to stop at the first constraint violation found
//
// This would be the equivalent of setting `Stop` on each constraint
StopOnFirst bool
// WhenConditions is the condition tokens that dictate under which conditions this validator is to be checked
//
// Condition tokens can be set and unset during validation to allow polymorphism of validation
// (see ValidatorContext.SetCondition & ValidatorContext.ClearCondition)
WhenConditions Conditions
// UnwantedConditions is the condition tokens that dictate when the property should not be present
UnwantedConditions Conditions
// RequiredWith is an expression of when this property is required according to the presence of other properties
//
// Use MustParseExpression or ParseExpression to build the expression - or build in code directly using
// combinations of OthersExpr, OtherProperty and OtherGrouping
RequiredWith OthersExpr
// RequiredWithMessage is the violation message to use when the RequiredWith fails (if this string is empty, then
// the default message is used)
RequiredWithMessage string
// UnwantedWith is an expression of when this property is unwanted according to the presence of other properties
//
// Use MustParseExpression or ParseExpression to build the expression - or build in code directly using
// combinations of OthersExpr, OtherProperty and OtherGrouping
UnwantedWith OthersExpr
// UnwantedWithMessage is the violation message to use when the UnwantedWith fails (if this string is empty, then
// the default message is used)
UnwantedWithMessage string
// Only when set to true, indicates that this should be the only property present
//
// When the property is specified alone - all other properties (including their constraints and even their mandatory status) are ignored
Only bool
// OnlyConditions is the condition tokens that dictate when the property should be the only property (see also Only)
OnlyConditions Conditions
// OnlyMessage is the violation message to use when the Only or OnlyConditions fails (i.e. the property is not the only property)
OnlyMessage string
// OasInfo is additional information (for OpenAPI Specification)
OasInfo *OasInfo
}
PropertyValidator is the individual validator for properties
func CreatePropertyValidator ¶
func CreatePropertyValidator(v8nTags ...string) *PropertyValidator
CreatePropertyValidator is the same as NewPropertyValidator - except that it panics if an error is encountered
func NewPropertyValidator ¶
func NewPropertyValidator(v8nTags ...string) (*PropertyValidator, error)
NewPropertyValidator creates a new PropertyValidator with the v8n tags supplied
NB. Each v8nTag can be an individual tag or a comma delimited list of tags
func (*PropertyValidator) AddConstraints ¶
func (pv *PropertyValidator) AddConstraints(c ...Constraint) *PropertyValidator
AddConstraints adds constraint(s) to the property validator
func (*PropertyValidator) AddMandatoryWhens ¶
func (pv *PropertyValidator) AddMandatoryWhens(c ...string) *PropertyValidator
AddMandatoryWhens adds mandatory when condition token(s) to the property validator
func (*PropertyValidator) AddUnwantedConditions ¶
func (pv *PropertyValidator) AddUnwantedConditions(c ...string) *PropertyValidator
AddUnwantedConditions adds when condition token(s) to the property validator
func (*PropertyValidator) AddWhenConditions ¶
func (pv *PropertyValidator) AddWhenConditions(c ...string) *PropertyValidator
AddWhenConditions adds when condition token(s) to the property validator
func (*PropertyValidator) Clone ¶
func (pv *PropertyValidator) Clone() *PropertyValidator
func (*PropertyValidator) MarshalJSON ¶
func (pv *PropertyValidator) MarshalJSON() ([]byte, error)
func (*PropertyValidator) SetMandatory ¶
func (pv *PropertyValidator) SetMandatory() *PropertyValidator
SetMandatory sets the property is mandatory (required) for the property validator
func (*PropertyValidator) SetNotNullable ¶
func (pv *PropertyValidator) SetNotNullable() *PropertyValidator
SetNotNullable sets the property validator to disallow nulls
func (*PropertyValidator) SetNullable ¶
func (pv *PropertyValidator) SetNullable() *PropertyValidator
SetNullable sets the property validator to allow nulls
func (*PropertyValidator) SetObjectValidator ¶
func (pv *PropertyValidator) SetObjectValidator(v *Validator) *PropertyValidator
SetObjectValidator sets the object validator for the property validator
func (*PropertyValidator) SetOptional ¶
func (pv *PropertyValidator) SetOptional() *PropertyValidator
SetOptional sets the property is optional for the property validator
func (*PropertyValidator) SetOrder ¶
func (pv *PropertyValidator) SetOrder(order int) *PropertyValidator
SetOrder sets the property check order for the property validator
func (*PropertyValidator) SetRequired ¶
func (pv *PropertyValidator) SetRequired() *PropertyValidator
SetRequired same as SetMandatory
func (*PropertyValidator) SetRequiredWith ¶
func (pv *PropertyValidator) SetRequiredWith(expr OthersExpr) *PropertyValidator
SetRequiredWith sets the required with expression for the property validator
func (*PropertyValidator) SetRequiredWithMessage ¶
func (pv *PropertyValidator) SetRequiredWithMessage(msg string) *PropertyValidator
SetRequiredWithMessage sets the required with message for the property validator
func (*PropertyValidator) SetType ¶
func (pv *PropertyValidator) SetType(t JsonType) *PropertyValidator
SetType sets the expected type for the property validator
func (*PropertyValidator) SetUnwantedWith ¶
func (pv *PropertyValidator) SetUnwantedWith(expr OthersExpr) *PropertyValidator
SetUnwantedWith sets the unwanted with expression for the property validator
func (*PropertyValidator) SetUnwantedWithMessage ¶
func (pv *PropertyValidator) SetUnwantedWithMessage(msg string) *PropertyValidator
SetUnwantedWithMessage sets the unwanted with message for the property validator
func (*PropertyValidator) ToV8nTagString ¶
func (pv *PropertyValidator) ToV8nTagString(options *V8nTagStringOptions) string
ToV8nTagString converts the property validator to its v8n tag representation string
Note: This method can panic if unable to convert one of the constraints to a v8n tag string. Although this should not occur with any built-in constraints it may happen on custom implemented constraints
type Range ¶
type Range struct {
// the minimum value of the range
Minimum float64
// the maximum value of the range
Maximum float64
// if set to true, ExclusiveMin specifies the minimum value is exclusive
ExclusiveMin bool
// if set to true, ExclusiveMax specifies the maximum value is exclusive
ExclusiveMax bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
Range constraint to check that a numeric value is within a specified minimum and maximum range
func (*Range) Check ¶
func (c *Range) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*Range) GetMessage ¶
func (c *Range) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type RangeInt ¶
type RangeInt struct {
// the minimum value of the range
Minimum int64
// the maximum value of the range
Maximum int64
// if set to true, ExclusiveMin specifies the minimum value is exclusive
ExclusiveMin bool
// if set to true, ExclusiveMax specifies the maximum value is exclusive
ExclusiveMax bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
RangeInt constraint to check that an integer value is within a specified minimum and maximum range
func (*RangeInt) Check ¶
func (c *RangeInt) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*RangeInt) GetMessage ¶
func (c *RangeInt) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type RegionalVariantTranslation ¶
type RegionalVariantTranslation struct {
// is the region (must not be "" or will not be added)
Region string
// the regional translation (if "" uses the parent language translation)
Translation string
}
RegionalVariantTranslation for use with Add...LanguageTranslation methods of Translator
type SetConditionFrom ¶
type SetConditionFrom struct {
// Parent by default, conditions are set on the current property or object - but specifying
// true for this field means the condition is set on the parent object too
Parent bool
// Global setting this field to true means the condition is set for the entire
// validator context
Global bool
// Prefix is any prefix to be appended to the condition token
Prefix string
// Mapping converts the string value to alternate values (if the value is not found in the map
// then the original value is used
Mapping map[string]string
// NullToken is the condition token used if the value of the property is null/nil. If this field is not set
// and the property value is null at validation - then a condition token of "null" is used
NullToken string
// Format is an optional format string for dealing with non-string property values
Format string
}
SetConditionFrom constraint is a utility constraint that can be used to set a condition in the ValidatorContext from the value of the property (to which this constraint is added)
Note: It will only set a condition if the property value is a string!
func (*SetConditionFrom) Check ¶
func (c *SetConditionFrom) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*SetConditionFrom) GetMessage ¶
func (c *SetConditionFrom) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type SetConditionIf ¶
type SetConditionIf struct {
// is the wrapped constraint to be checked
//
// If this is nil, the SetOk condition is always set
//
// Note: the wrapped constraint cannot add any violations and cannot stop the validation (i.e. it is called 'silently')
Constraint Constraint
// is the condition to set if the wrapped constraint is ok
//
// Note: if this is an empty string - no condition is set
SetOk string
// is the condition to set if the wrapped constraint fails
//
// Note: if this is an empty string - no condition is set
SetFail string
// Parent by default, conditions are set on the current property or object - but specifying
// true for this field means the condition is set on the parent object too
Parent bool
// Global setting this field to true means the condition is set for the entire
// validator context
Global bool
}
SetConditionIf is a special constraint that wraps another constraint and sets a condition based on whether that wrapped constraint is ok or fails
Note: the wrapped constraint cannot add any violations and cannot stop the validation (i.e. it is called 'silently')
func (*SetConditionIf) Check ¶
func (c *SetConditionIf) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*SetConditionIf) GetMessage ¶
func (c *SetConditionIf) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
func (*SetConditionIf) MarshalJSON ¶
func (c *SetConditionIf) MarshalJSON() ([]byte, error)
func (*SetConditionIf) UnmarshalJSON ¶
func (c *SetConditionIf) UnmarshalJSON(data []byte) error
type SetConditionOnType ¶
type SetConditionOnType struct{}
SetConditionOnType constraint is a utility constraint that can be used to set a condition in the ValidatorContext indicating the type of the property value to which this constraint is added.
The condition token set will be at least one of the following:
"type_null", "type_object", "type_array", "type_boolean", "type_string", "type_integer", "type_number", "type_unknown"
Note that an int value will set both "type_number" and "type_integer" (because an int is both)
On detecting a value represented by a json.Number - the "type_number" will always be set. And this may also be complimented by the "type_integer" (if the json.Number holds an int value)
Also, with json.Number values, the following condition tokens may also be set
"type_invalid_number", "type_nan", "type_inf"
("type_invalid_number" indicating that the json.Number could not be parsed to either int or float)
When handling json.Number values, This constraint can be used in conjunction with a following FailWhen constraint to enforce failures in case of Inf, Nan or unparseable
func (*SetConditionOnType) Check ¶
func (c *SetConditionOnType) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*SetConditionOnType) GetMessage ¶
func (c *SetConditionOnType) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type SetConditionProperty ¶
type SetConditionProperty struct {
// PropertyName is the name of the property to extract the condition value from
PropertyName string `v8n:"default"`
// Prefix is any prefix to be appended to the condition token
Prefix string
// Mapping converts the token value to alternate values (if the value is not found in the map
// then the original value is used)
Mapping map[string]string
// NullToken is the condition token used if the value of the property specified is null/nil. If this field is not set
// and the property value is null at validation - then a condition token of "null" is used
NullToken string
// MissingToken is the condition token used if the property specified is missing. If this field is not set
// and the property is missing at validation - then a condition token of "missing" is used
MissingToken string
// Format is an optional format string for dealing with non-string property values
Format string
}
SetConditionProperty constraint is a utility constraint that can be used to set a condition in the ValidatorContext from the value of a specified property within the object to which this constraint is attached
This constraint is normally only used in Validator.Constraints ¶
Note: The property value can be of any type (inc. null) or, indeed, the property may be missing
func (*SetConditionProperty) Check ¶
func (c *SetConditionProperty) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*SetConditionProperty) GetMessage ¶
func (c *SetConditionProperty) GetMessage(tcx I18nContext) string
type StringCharacters ¶
type StringCharacters struct {
// the ranges of characters (runes) that are allowed - if this slice is non-empty, each character must be in at least one of these
AllowRanges []unicode.RangeTable
// the named ranges of characters (runes) that are allowed - if this slice is non-empty, each character must be in at least one of these
//
// The named ranges can be:
//
// * "BMP", "SMP" or "SIP" (Basic Multilingual Plane, Supplementary Multilingual Plane or Supplementary Ideographic Plane respectively)
//
// * any name from unicode.Categories prefixed with "Category-"
//
// * any name from unicode.Scripts prefixed with "Script-"
//
// * any name from unicode.Properties prefixed with "Property-"
//
// * any name from unicode.FoldCategory prefixed with "FoldCategory-"
//
// * any name from unicode.FoldScript prefixed with "FoldScript-"
NamedAllowRanges []string
// the ranges of characters (runes) that are not allowed - if any character
// is in any of these ranges then the constraint is violated
DisallowRanges []unicode.RangeTable
// the named ranges of characters (runes) that are not allowed - if any character
// is in any of these ranges then the constraint is violated
//
// The named ranges can be:
//
// * "BMP", "SMP" or "SIP" (Basic Multilingual Plane, Supplementary Multilingual Plane or Supplementary Ideographic Plane respectively)
//
// * any name from unicode.Categories prefixed with "Category-"
//
// * any name from unicode.Scripts prefixed with "Script-"
//
// * any name from unicode.Properties prefixed with "Property-"
//
// * any name from unicode.FoldCategory prefixed with "FoldCategory-"
//
// * any name from unicode.FoldScript prefixed with "FoldScript-"
NamedDisallowRanges []string
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
StringCharacters constraint to check that a string contains only allowable characters (and does not contain any disallowed characters)
func (*StringCharacters) Check ¶
func (c *StringCharacters) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringCharacters) GetMessage ¶
func (c *StringCharacters) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringContains ¶
type StringContains struct {
// the value to check that the string contains
Value string `v8n:"default"`
// multiple additional values that the string may contain
Values []string
// whether the check is case-insensitive (by default, the check is case-sensitive)
CaseInsensitive bool
// whether the check is NOT-ed (i.e. checks that the string does not contain)
Not bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
StringContains constraint to check that a string contains with a given value
func (*StringContains) Check ¶
func (c *StringContains) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringContains) GetMessage ¶
func (c *StringContains) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringEndsWith ¶
type StringEndsWith struct {
// the value to check that the string ends with
Value string `v8n:"default"`
// multiple additional values that the string may end with
Values []string
// whether the check is case-insensitive (by default, the check is case-sensitive)
CaseInsensitive bool
// whether the check is NOT-ed (i.e. checks that the string does not end with)
Not bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
StringEndsWith constraint to check that a string ends with a given suffix
func (*StringEndsWith) Check ¶
func (c *StringEndsWith) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringEndsWith) GetMessage ¶
func (c *StringEndsWith) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringExactLength ¶
type StringExactLength struct {
// the exact length expected
Value int `v8n:"default"`
// if set to true, uses the rune length (true Unicode length) to check length of string
UseRuneLen bool
// is the optional unicode normalisation form to be used prior to checking length (no unicode normalisation is performed if this is empty or unknown form)
NormalisationForm string
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
StringExactLength constraint to check that a string has an exact length
func (*StringExactLength) Check ¶
func (c *StringExactLength) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringExactLength) GetMessage ¶
func (c *StringExactLength) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringGreaterThan ¶
type StringGreaterThan struct {
// the value to compare against
Value string `v8n:"default"`
// when set, the comparison is case-insensitive
CaseInsensitive bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
StringGreaterThan constraint to check that a string value is greater than a specified value
Note: this constraint is strict - if the property value is not a string then this constraint fails
func (*StringGreaterThan) Check ¶
func (c *StringGreaterThan) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringGreaterThan) GetMessage ¶
func (c *StringGreaterThan) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringGreaterThanOrEqual ¶
type StringGreaterThanOrEqual struct {
// the value to compare against
Value string `v8n:"default"`
// when set, the comparison is case-insensitive
CaseInsensitive bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
StringGreaterThanOrEqual constraint to check that a string value is greater than or equal to a specified value
Note: this constraint is strict - if the property value is not a string then this constraint fails
func (*StringGreaterThanOrEqual) Check ¶
func (c *StringGreaterThanOrEqual) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringGreaterThanOrEqual) GetMessage ¶
func (c *StringGreaterThanOrEqual) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringGreaterThanOrEqualOther ¶
type StringGreaterThanOrEqualOther struct {
// the property name of the other value to compare against
//
// Note: the PropertyName can also be JSON dot notation path - where leading dots allow traversal up
// the object tree and names, separated by dots, allow traversal down the object tree.
// A single dot at start is equivalent to no starting dot (i.e. a property name at the same level)
PropertyName string `v8n:"default"`
// when set, the comparison is case-insensitive
CaseInsensitive bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
StringGreaterThanOrEqualOther constraint to check that a string value is greater than or equal to another named property value
Note: this constraint is strict - if either property value is not a string then this constraint fails
func (*StringGreaterThanOrEqualOther) Check ¶
func (c *StringGreaterThanOrEqualOther) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringGreaterThanOrEqualOther) GetMessage ¶
func (c *StringGreaterThanOrEqualOther) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringGreaterThanOther ¶
type StringGreaterThanOther struct {
// the property name of the other value to compare against
//
// Note: the PropertyName can also be JSON dot notation path - where leading dots allow traversal up
// the object tree and names, separated by dots, allow traversal down the object tree.
// A single dot at start is equivalent to no starting dot (i.e. a property name at the same level)
PropertyName string `v8n:"default"`
// when set, the comparison is case-insensitive
CaseInsensitive bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
StringGreaterThanOther constraint to check that a string value is greater than another named property value
Note: this constraint is strict - if either property value is not a string then this constraint fails
func (*StringGreaterThanOther) Check ¶
func (c *StringGreaterThanOther) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringGreaterThanOther) GetMessage ¶
func (c *StringGreaterThanOther) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringLength ¶
type StringLength struct {
// the minimum length
Minimum int
// the maximum length (only checked if this value is > 0)
Maximum int
// if set to true, ExclusiveMin specifies the minimum value is exclusive
ExclusiveMin bool
// if set to true, ExclusiveMax specifies the maximum value is exclusive
ExclusiveMax bool
// if set to true, uses the rune length (true Unicode length) to check length of string
UseRuneLen bool
// is the optional unicode normalisation form to be used prior to checking length (no unicode normalisation is performed if this is empty or unknown form)
NormalisationForm string
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
StringLength constraint to check that a string has a minimum and maximum length
func (*StringLength) Check ¶
func (c *StringLength) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringLength) GetMessage ¶
func (c *StringLength) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringLessThan ¶
type StringLessThan struct {
// the value to compare against
Value string `v8n:"default"`
// when set, the comparison is case-insensitive
CaseInsensitive bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
StringLessThan constraint to check that a string value is less than a specified value
Note: this constraint is strict - if the property value is not a string then this constraint fails
func (*StringLessThan) Check ¶
func (c *StringLessThan) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringLessThan) GetMessage ¶
func (c *StringLessThan) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringLessThanOrEqual ¶
type StringLessThanOrEqual struct {
// the value to compare against
Value string `v8n:"default"`
// when set, the comparison is case-insensitive
CaseInsensitive bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
StringLessThanOrEqual constraint to check that a string value is less than or equal to a specified value
Note: this constraint is strict - if the property value is not a string then this constraint fails
func (*StringLessThanOrEqual) Check ¶
func (c *StringLessThanOrEqual) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringLessThanOrEqual) GetMessage ¶
func (c *StringLessThanOrEqual) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringLessThanOrEqualOther ¶
type StringLessThanOrEqualOther struct {
// the property name of the other value to compare against
//
// Note: the PropertyName can also be JSON dot notation path - where leading dots allow traversal up
// the object tree and names, separated by dots, allow traversal down the object tree.
// A single dot at start is equivalent to no starting dot (i.e. a property name at the same level)
PropertyName string `v8n:"default"`
// when set, the comparison is case-insensitive
CaseInsensitive bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
StringLessThanOrEqualOther constraint to check that a string value is less than or equal to another named property value
Note: this constraint is strict - if either property value is not a string then this constraint fails
func (*StringLessThanOrEqualOther) Check ¶
func (c *StringLessThanOrEqualOther) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringLessThanOrEqualOther) GetMessage ¶
func (c *StringLessThanOrEqualOther) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringLessThanOther ¶
type StringLessThanOther struct {
// the property name of the other value to compare against
//
// Note: the PropertyName can also be JSON dot notation path - where leading dots allow traversal up
// the object tree and names, separated by dots, allow traversal down the object tree.
// A single dot at start is equivalent to no starting dot (i.e. a property name at the same level)
PropertyName string `v8n:"default"`
// when set, the comparison is case-insensitive
CaseInsensitive bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
StringLessThanOther constraint to check that a string value is less than another named property value
Note: this constraint is strict - if either property value is not a string then this constraint fails
func (*StringLessThanOther) Check ¶
func (c *StringLessThanOther) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringLessThanOther) GetMessage ¶
func (c *StringLessThanOther) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringLowercase ¶
type StringLowercase struct {
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string `v8n:"default"`
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
StringLowercase constraint to check that a string has only lowercase letters
func (*StringLowercase) Check ¶
func (c *StringLowercase) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringLowercase) GetMessage ¶
func (c *StringLowercase) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringMaxLength ¶
type StringMaxLength struct {
// the maximum length value
Value int `v8n:"default"`
// when set to true, ExclusiveMax specifies the maximum value is exclusive
ExclusiveMax bool
// if set to true, uses the rune length (true Unicode length) to check length of string
UseRuneLen bool
// is the optional unicode normalisation form to be used prior to checking length (no unicode normalisation is performed if this is empty or unknown form)
NormalisationForm string
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
StringMaxLength constraint to check that a string has a maximum length
func (*StringMaxLength) Check ¶
func (c *StringMaxLength) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringMaxLength) GetMessage ¶
func (c *StringMaxLength) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringMinLength ¶
type StringMinLength struct {
// the minimum length value
Value int `v8n:"default"`
// when set to true, ExclusiveMin specifies the minimum value is exclusive
ExclusiveMin bool
// if set to true, uses the rune length (true Unicode length) to check length of string
UseRuneLen bool
// is the optional unicode normalisation form to be used prior to checking length (no unicode normalisation is performed if this is empty or unknown form)
NormalisationForm string
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
StringMinLength constraint to check that a string has a minimum length
func (*StringMinLength) Check ¶
func (c *StringMinLength) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringMinLength) GetMessage ¶
func (c *StringMinLength) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringNoControlCharacters ¶
type StringNoControlCharacters struct {
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string `v8n:"default"`
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
StringNoControlCharacters constraint to check that a string does not contain any control characters (i.e. chars < 32)
func (*StringNoControlCharacters) Check ¶
func (c *StringNoControlCharacters) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringNoControlCharacters) GetMessage ¶
func (c *StringNoControlCharacters) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringNotBlank ¶
type StringNotBlank struct {
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string `v8n:"default"`
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
StringNotBlank constraint to check that string value is not blank (i.e. that after removing leading and trailing whitespace the value is not an empty string)
func (*StringNotBlank) Check ¶
func (c *StringNotBlank) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringNotBlank) GetMessage ¶
func (c *StringNotBlank) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringNotEmpty ¶
type StringNotEmpty struct {
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string `v8n:"default"`
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
StringNotEmpty constraint to check that string value is not empty (i.e. not "")
func (*StringNotEmpty) Check ¶
func (c *StringNotEmpty) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringNotEmpty) GetMessage ¶
func (c *StringNotEmpty) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringPattern ¶
type StringPattern struct {
// the regexp pattern that the string value must match
Regexp regexp.Regexp `v8n:"default"`
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
StringPattern constraint to check that a string matches a given regexp pattern
func (*StringPattern) Check ¶
func (c *StringPattern) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringPattern) GetMessage ¶
func (c *StringPattern) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
func (*StringPattern) MarshalJSON ¶
func (c *StringPattern) MarshalJSON() ([]byte, error)
func (*StringPattern) UnmarshalJSON ¶
func (c *StringPattern) UnmarshalJSON(data []byte) error
type StringPresetPattern ¶
type StringPresetPattern struct {
// the preset token (which must exist in the PatternPresets map)
//
// If the specified preset token does not exist - the constraint fails!
Preset string `v8n:"default"`
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
StringPresetPattern constraint to check that a string matches a given preset pattern
Preset patterns are defined in PatternPresets (add your own where required)
Messages for the preset patterns are defined in PatternPresetMessages ¶
If the preset pattern requires some extra validation beyond the regexp match, then add a checker to the PatternPresetPostPatternChecks variable
func (*StringPresetPattern) Check ¶
func (c *StringPresetPattern) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringPresetPattern) GetMessage ¶
func (c *StringPresetPattern) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringStartsWith ¶
type StringStartsWith struct {
// the value to check that the string starts with
Value string `v8n:"default"`
// multiple additional values that the string may start with
Values []string
// whether the check is case-insensitive (by default, the check is case-sensitive)
CaseInsensitive bool
// whether the check is NOT-ed (i.e. checks that the string does not start with)
Not bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
StringStartsWith constraint to check that a string starts with a given prefix
func (*StringStartsWith) Check ¶
func (c *StringStartsWith) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringStartsWith) GetMessage ¶
func (c *StringStartsWith) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringUppercase ¶
type StringUppercase struct {
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string `v8n:"default"`
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
StringUppercase constraint to check that a string has only uppercase letters
func (*StringUppercase) Check ¶
func (c *StringUppercase) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringUppercase) GetMessage ¶
func (c *StringUppercase) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringValidCardNumber ¶
type StringValidCardNumber struct {
// if set to true, AllowSpaces accepts space separators in the card number (but must appear between each 4 digits)
AllowSpaces bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string `v8n:"default"`
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
StringValidCardNumber constraint checks that a string contains a valid card number according to Luhn Algorithm and checking that card number is 10 to 19 digits
func (*StringValidCardNumber) Check ¶
func (c *StringValidCardNumber) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringValidCardNumber) GetMessage ¶
func (c *StringValidCardNumber) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringValidCountryCode ¶
type StringValidCountryCode struct {
Allow3166_2 bool
Allow3166_2_Obsoletes bool
AllowUserAssigned bool
Allow3166_1_ExceptionallyReserved bool
Allow3166_1_IndeterminatelyReserved bool
Allow3166_1_TransitionallyReserved bool
Allow3166_1_Deleted bool
Allow3166_1_Numeric bool
// overrides all other flags (with the exception of AllowUserAssigned) and allows only ISO-3166-1 numeric codes
NumericOnly bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string `v8n:"default"`
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
StringValidCountryCode constraint checks that a string is a valid ISO-3166 (3166-1 / 3166-2) country code
func (*StringValidCountryCode) Check ¶
func (c *StringValidCountryCode) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringValidCountryCode) GetMessage ¶
func (c *StringValidCountryCode) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringValidCurrencyCode ¶
type StringValidCurrencyCode struct {
AllowNumeric bool
AllowHistorical bool
AllowUnofficial bool
AllowCrypto bool
// AllowTestCode when set to true, allows test currency codes (i.e. "XTS" or numeric "963")
AllowTestCode bool
// AllowNoCode when set to true, allows no code (i.e. "XXX" or numeric "999")
AllowNoCode bool
// set to true to only allow ISO-4217 numeric currency codes
NumericOnly bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string `v8n:"default"`
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
StringValidCurrencyCode constraint checks that a string is a valid ISO-4217 currency code
func (*StringValidCurrencyCode) Check ¶
func (c *StringValidCurrencyCode) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringValidCurrencyCode) GetMessage ¶
func (c *StringValidCurrencyCode) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringValidEmail ¶
type StringValidEmail struct {
// DisallowRFC5322 when set, disallows email addresses in RFC5322 format (i.e "Barry Gibbs <[email protected]>")
DisallowRFC5322 bool
// CheckExchange when set, checks the MX (mail exchange) for the email address
CheckExchange bool
// AllowIPAddress when set, allows email addresses with IP (e.g. "me@[123.0.1.2]")
AllowIPAddress bool
// AllowIPV6 when set, allows email addresses with IP v6 (e.g. "me@[2001:db8::68]")
AllowIPV6 bool
// AllowLocal when set, allows email addresses with 'local' (e.g. "me@localhost", "me@local", "me@localdomain", "me@[127.0.0.1]", "me@[::1]")
AllowLocal bool
// AllowTldOnly when set, allows email addresses with only Tld specified (e.g. "me@audi")
AllowTldOnly bool
// AllowGeographicTlds when set, allows email addresses with geographic Tlds (e.g. "[email protected]")
AllowGeographicTlds bool
// AllowGenericTlds when set, allows email addresses with generic Tlds (e.g. "[email protected]")
AllowGenericTlds bool
// AllowBrandTlds when set, allows email addresses with brand Tlds (e.g. "[email protected]")
AllowBrandTlds bool
// AllowInfraTlds when set, allows email addresses with infrastructure Tlds (e.g. "me@arpa")
AllowInfraTlds bool
// AllowTestTlds when set, allows email addresses with test Tlds and test domains (e.g. "[email protected]", "[email protected]")
AllowTestTlds bool
// AddCountryCodeTlds is an optional slice of additional country (and geographic) Tlds to allow
AddCountryCodeTlds []string
// ExcCountryCodeTlds is an optional slice of country (and geographic) Tlds to disallow
ExcCountryCodeTlds []string
// AddGenericTlds is an optional slice of additional generic Tlds to allow (only checked if AllowGenericTlds is also set)
AddGenericTlds []string
// ExcGenericTlds is an optional slice of generic Tlds to disallow (only relevant if AllowGenericTlds is also set)
ExcGenericTlds []string
// AddBrandTlds is an optional slice of additional brand Tlds to allow (only checked if AllowBrandTlds is also set)
AddBrandTlds []string
// ExcBrandTlds is an optional slice of brand Tlds to disallow (only relevant if AllowBrandTlds is also set)
ExcBrandTlds []string
// AddLocalTlds is an optional slice of additional local Tlds to allow (only checked if AllowLocal is also set)
AddLocalTlds []string
// ExcLocalTlds is an optional slice of local Tlds to disallow (only relevant if AllowLocal is also set)
ExcLocalTlds []string
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string `v8n:"default"`
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
StringValidEmail constraint checks that a string contains a valid email address (does not verify the email address!)
NB. Uses mail.ParseAddress to check valid email address
func (*StringValidEmail) Check ¶
func (c *StringValidEmail) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringValidEmail) GetMessage ¶
func (c *StringValidEmail) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringValidISODate ¶
type StringValidISODate struct {
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string `v8n:"default"`
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
StringValidISODate constraint checks that a string value is a valid ISO8601 Date format (excluding time)
func (*StringValidISODate) Check ¶
func (c *StringValidISODate) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringValidISODate) GetMessage ¶
func (c *StringValidISODate) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringValidISODatetime ¶
type StringValidISODatetime struct {
// specifies, if set to true, that time offsets are not permitted
NoOffset bool
// specifies, if set to true, that seconds cannot have decimal places
NoMillis bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string `v8n:"default"`
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
StringValidISODatetime constraint checks that a string value is a valid ISO8601 Date/time format
func (*StringValidISODatetime) Check ¶
func (c *StringValidISODatetime) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringValidISODatetime) GetMessage ¶
func (c *StringValidISODatetime) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringValidISODuration ¶
type StringValidISODuration struct {
// if set, disallows negative durations (e.g. "-P1Y")
DisallowNegative bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string `v8n:"default"`
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
StringValidISODuration constraint checks that a string value is a valid ISO8601 Duration
func (*StringValidISODuration) Check ¶
func (c *StringValidISODuration) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringValidISODuration) GetMessage ¶
func (c *StringValidISODuration) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringValidJson ¶
type StringValidJson struct {
DisallowNullJson bool
DisallowValue bool
DisallowArray bool
DisallowObject bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string `v8n:"default"`
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
StringValidJson constraint checks that a string is valid json
func (*StringValidJson) Check ¶
func (c *StringValidJson) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringValidJson) GetMessage ¶
func (c *StringValidJson) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringValidLanguageCode ¶
type StringValidLanguageCode struct {
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string `v8n:"default"`
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
StringValidLanguageCode constraint checks that a string is a valid BCP-47 language code
NB. Uses language.Parse to check valid language code
func (*StringValidLanguageCode) Check ¶
func (c *StringValidLanguageCode) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringValidLanguageCode) GetMessage ¶
func (c *StringValidLanguageCode) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringValidTimezone ¶
type StringValidTimezone struct {
// allows location only
LocationOnly bool
// allows offset only
OffsetOnly bool
// if set, allows offset to be a numeric value
AllowNumeric bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string `v8n:"default"`
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
}
StringValidTimezone constraint checks that a string value is a valid timezone
NB. If both LocationOnly and OffsetOnly are set to true - this constraint will always fail!
func (*StringValidTimezone) Check ¶
func (c *StringValidTimezone) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringValidTimezone) GetMessage ¶
func (c *StringValidTimezone) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringValidToken ¶
type StringValidToken struct {
// the set of allowed tokens for the string
Tokens []string `v8n:"default"`
// set to true to make the token check case in-sensitive
IgnoreCase bool
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
StringValidToken constraint checks that a string matches one of a pre-defined list of tokens
func (*StringValidToken) Check ¶
func (c *StringValidToken) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringValidToken) GetMessage ¶
func (c *StringValidToken) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringValidUnicodeNormalization ¶
type StringValidUnicodeNormalization struct {
// the normalization form required - i.e. "NFC", "NFKC", "NFD" or "NFKD"
//
// (from package "golang.org/x/text/unicode/norm")
Form string `v8n:"default"`
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
StringValidUnicodeNormalization constraint to check that a string has the correct Unicode normalization form
func (*StringValidUnicodeNormalization) Check ¶
func (c *StringValidUnicodeNormalization) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringValidUnicodeNormalization) GetMessage ¶
func (c *StringValidUnicodeNormalization) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type StringValidUuid ¶
type StringValidUuid struct {
// the minimum UUID version (optional - if zero this is not checked)
MinVersion uint8
// the specific UUID version (optional - if zero this is not checked)
SpecificVersion uint8
// the violation message to be used if the constraint fails (see Violation.Message)
//
// (if the Message is an empty string then the default violation message is used)
Message string `v8n:"default"`
// when set to true, Stop prevents further validation checks on the property if this constraint fails
Stop bool
// when set to true, fails if the value being checked is not a correct type
Strict bool
}
StringValidUuid constraint to check that a string value is a valid UUID
func (*StringValidUuid) Check ¶
func (c *StringValidUuid) Check(v interface{}, vcx *ValidatorContext) (bool, string)
Check implements Constraint.Check
func (*StringValidUuid) GetMessage ¶
func (c *StringValidUuid) GetMessage(tcx I18nContext) string
GetMessage implements the Constraint.GetMessage
type TagAliases ¶
type TagHandler ¶
type TagHandler interface {
Handle(tag string, tagValue string, commaParsed []string, pv *PropertyValidator, fld reflect.StructField) error
}
TagHandler is the interface for handling custom tags
Custom tags are used when building validators from structs using valix.ValidatorFor
type Time ¶
Time is an optional replacement of time.Time
For use with struct fields where unmarshalling needs to be less strict than just RFC3339
func (*Time) MarshalJSON ¶
func (*Time) UnmarshalJSON ¶
type Translator ¶
type Translator interface {
TranslateToken(lang string, region string, token string) string
TranslateMessage(lang string, region string, message string) string
TranslateFormat(lang string, region string, format string, a ...interface{}) string
AddTokenLanguageTranslation(lang string, token string, translation string, regionals ...RegionalVariantTranslation)
AddMessageLanguageTranslation(lang string, message string, translation string, regionals ...RegionalVariantTranslation)
AddFormatLanguageTranslation(lang string, format string, translation string, regionals ...RegionalVariantTranslation)
AddTokenRegionTranslation(lang string, region string, token string, translation string)
AddMessageRegionTranslation(lang string, region string, message string, translation string)
AddFormatRegionTranslation(lang string, region string, format string, translation string)
}
var DefaultTranslator Translator = defaultInternalTranslator
DefaultTranslator is the default translator used by valix I18n support
Replace it with your own where necessary
type V8nTagStringOptions ¶
type V8nTagStringOptions struct {
// if set to true, constraint names are abbreviated in the resulting v8n tag string
AbbreviateConstraintNames bool
// if set to true, constraint field names are abbreviated in the resulting v8n tag string
AbbreviateFieldNames bool
// the minimum (desired) length for abbreviated constraint field names (the default 0 is the same as setting to 3)
MinimumFieldNameLength uint
// if set to true, constraints where no fields are set have the trailing {} dropped
DiscardUnneededCurlies bool
// if set to true, conditional constraints are not unwrapped (i.e. not reduced to their short form)
NoUnwrapConditionalConstraints bool
// if set to true, does not put spaces between each v8n tag token
UnSpaced bool
}
V8nTagStringOptions is used by PropertyValidator.ToV8nTagString to control the output v8n tag format
type ValidationError ¶
func (*ValidationError) Error ¶
func (ve *ValidationError) Error() string
type Validator ¶
type Validator struct {
// IgnoreUnknownProperties is whether to ignore unknown properties (default false)
//
// Set this to `true` if you want to allow unknown properties
IgnoreUnknownProperties bool
// Properties is the map of property names (key) and PropertyValidator (value)
Properties Properties
// Constraints is an optional slice of Constraint items to be checked on the object/array
//
// * These are checked in the order specified and prior to property validator & unknown property checks
Constraints Constraints
// AllowArray denotes, when true (default is false), that this validator will allow a JSON array - where each
// item in the array can be validated as an object
AllowArray bool
// AllowNullItems [for arrays only] denotes whether null array items are allowed
AllowNullItems bool
// DisallowObject denotes, when set to true, that this validator will disallow JSON objects - i.e. that it
// expects JSON arrays (in which case the AllowArray should also be set to true)
DisallowObject bool
// AllowNullJson forces RequestValidate to accept a request body that is null JSON (i.e. a body containing just `null`)
AllowNullJson bool
// StopOnFirst if set, instructs the validator to stop at the first violation found
StopOnFirst bool
// UseNumber forces RequestValidate method to use json.Number when decoding request body
UseNumber bool
// OrderedPropertyChecks determines whether properties should be checked in order - when set to true, properties
// are sorted by PropertyValidator.Order and property name
//
// When this is set to false (default) properties are checked in the order in which they appear in the properties map -
// which is unpredictable
//
// Note: If any of the properties in the validator has PropertyValidator.Order set to a non-zero value
// then ordered property checks are also performed
OrderedPropertyChecks bool
// WhenConditions is the condition tokens that dictate under which conditions this validator is to be checked
//
// Condition tokens can be set and unset during validation to allow polymorphism of validation
// (see ValidatorContext.SetCondition & ValidatorContext.ClearCondition)
WhenConditions Conditions
// ConditionalVariants represents a slice of ConditionalVariant items - where the first one that has the condition
// satisfied is used (only one is ever used!)
//
// If none of the conditionals is satisfied, the validation falls back to using the
// parent (this) Validator
//
// Condition tokens can be set and unset during validation to allow polymorphism of validation
// (see ValidatorContext.SetCondition & ValidatorContext.ClearCondition)
ConditionalVariants ConditionalVariants
// OasInfo is additional information (for OpenAPI Specification) - used for generating and reading OAS
OasInfo *OasInfo
}
Validator is the validator against which requests, maps and slices can be checked
var PropertyValidatorValidator *Validator
var ValidatorValidator *Validator
func MustCompileValidatorFor ¶
MustCompileValidatorFor creates a Validator for a specified struct
Similar to ValidatorFor but rather than returning an error, it panics if a Validator cannot be compiled for the struct
func ValidatorFor ¶
ValidatorFor creates a Validator for a specified struct
If a Validator cannot be compiled for the supplied struct an error is returned ¶
When evaluating the supplied struct to build a Validator, tags on the struct fields are used to further clarify the validation constraints. These are specified using the `v8n` tag (see full documentation for details of this tag)
The `json` tag is also used, if specified, to determine the JSON property name to be used.
func (*Validator) IsOrderedPropertyChecks ¶
func (*Validator) MarshalJSON ¶
func (*Validator) RequestQueryValidate ¶
func (v *Validator) RequestQueryValidate(req *http.Request, initialConditions ...string) (bool, []*Violation, interface{})
RequestQueryValidate Performs validation on the request query (http.Request.URL.Query) of the supplied http.Request
If the validation of the request query fails, false is returned and the returned violations give the reason(s) for the validation failure.
If the validation is successful, the validated query (as JSON object) is also returned
func (*Validator) RequestQueryValidateInto ¶
func (v *Validator) RequestQueryValidateInto(req *http.Request, value interface{}, initialConditions ...string) (bool, []*Violation, interface{})
RequestQueryValidateInto performs validation on the request query (http.Request.URL.Query) of the supplied http.Request and, if validation successful, attempts to unmarshall the query params into the supplied value
func (*Validator) RequestValidate ¶
func (v *Validator) RequestValidate(req *http.Request, initialConditions ...string) (bool, []*Violation, interface{})
RequestValidate Performs validation on the request body of the supplied http.Request
If the validation of the request body fails, false is returned and the returned violations give the reason(s) for the validation failure.
If the validation is successful, the validated JSON (object or array) is also returned - as represented by (if the body was a JSON object)
map[string]interface{}
or as represented by (if the body was a JSON array)
[]interface{}
func (*Validator) RequestValidateInto ¶
func (v *Validator) RequestValidateInto(req *http.Request, value interface{}, initialConditions ...string) (bool, []*Violation, interface{})
RequestValidateInto performs validation on the request body (representing JSON) and, if validation successful, attempts to unmarshall the JSON into the supplied value
func (*Validator) Validate ¶
func (v *Validator) Validate(obj map[string]interface{}, initialConditions ...string) (bool, []*Violation)
Validate performs validation on the supplied JSON object
Where the JSON object is represented as an unmarshalled
map[string]interface{}
func (*Validator) ValidateArrayOf ¶
func (v *Validator) ValidateArrayOf(arr []interface{}, initialConditions ...string) (bool, []*Violation)
ValidateArrayOf Performs validation on each element of the supplied JSON array
Where the JSON array is represented as an unmarshalled
[]interface{}
and each item of the slice is expected to be a JSON object represented as an unmarshalled
map[string]interface{}
func (*Validator) ValidateInto ¶
ValidateInto performs validation on the supplied data (representing JSON) and, if validation successful, attempts to unmarshall the JSON into the supplied value
If validation is unsuccessful (i.e. any violations) this method returns a ValidationError
func (*Validator) ValidateReader ¶
func (v *Validator) ValidateReader(r io.Reader, initialConditions ...string) (bool, []*Violation, interface{})
ValidateReader performs validation on the supplied reader (representing JSON)
func (*Validator) ValidateReaderInto ¶
func (v *Validator) ValidateReaderInto(r io.Reader, value interface{}, initialConditions ...string) (bool, []*Violation, interface{})
ValidateReaderInto performs validation on the supplied reader (representing JSON) and, if validation successful, attempts to unmarshall the JSON into the supplied value
func (*Validator) ValidateString ¶
func (v *Validator) ValidateString(s string, initialConditions ...string) (bool, []*Violation, interface{})
ValidateString performs validation on the supplied string (representing JSON)
func (*Validator) ValidateStringInto ¶
func (v *Validator) ValidateStringInto(s string, value interface{}, initialConditions ...string) (bool, []*Violation, interface{})
ValidateStringInto performs validation on the supplied string (representing JSON) and, if validation successful, attempts to unmarshall the JSON into the supplied value
type ValidatorContext ¶
type ValidatorContext struct {
// contains filtered or unexported fields
}
ValidatorContext is the context that is generated by the Validator and passed to each descendant Validator, PropertyValidator and each Constraint.Check function
func (*ValidatorContext) AddViolation ¶
func (vc *ValidatorContext) AddViolation(v *Violation)
AddViolation adds a Violation to the validation context
Note: Adding a violation always causes the validator to fail!
func (*ValidatorContext) AddViolationForCurrent ¶
func (vc *ValidatorContext) AddViolationForCurrent(msg string, translate bool, codes ...interface{})
AddViolationForCurrent adds a Violation to the validation context for the current property and path
Note 1: Use the `translate` arg to determine if the message is to be i18n translated
Note 2: Adding a violation always causes the validator to fail!
func (*ValidatorContext) AncestorArrayIndex ¶
func (vc *ValidatorContext) AncestorArrayIndex(level uint) (*int, bool)
AncestorArrayIndex returns an ancestor array index (or nil if ancestor is a property name)
func (*ValidatorContext) AncestorPath ¶
func (vc *ValidatorContext) AncestorPath(level uint) (*string, bool)
AncestorPath returns an ancestor property path
The level determines how far up the ancestry - 0 is parent, 1 is grandparent, etc.
func (*ValidatorContext) AncestorProperty ¶
func (vc *ValidatorContext) AncestorProperty(level uint) (interface{}, bool)
AncestorProperty returns an ancestor property - which may be a string (for property name) or an int (for array index)
Alternatively, to obtain an ancestor property name use...
AncestorPropertyName
or an ancestor array index use...
AncestorArrayIndex
func (*ValidatorContext) AncestorPropertyName ¶
func (vc *ValidatorContext) AncestorPropertyName(level uint) (*string, bool)
AncestorPropertyName returns an ancestor property name (or nil if ancestor property is an array index)
func (*ValidatorContext) AncestorValue ¶
func (vc *ValidatorContext) AncestorValue(level uint) (interface{}, bool)
AncestorValue returns an ancestor value
func (*ValidatorContext) AncestryIndex ¶
func (vc *ValidatorContext) AncestryIndex(level uint) (index int, max int, ok bool)
func (*ValidatorContext) CeaseFurther ¶
func (vc *ValidatorContext) CeaseFurther()
CeaseFurther causes further constraints and property validators on the current property to be ceased (i.e. not performed)
Note: This does not affect whether the validator succeeds or fails
func (*ValidatorContext) CeaseFurtherIf ¶
func (vc *ValidatorContext) CeaseFurtherIf(condition bool)
CeaseFurtherIf causes further constraints and property validators on the current property to be ceased if the condition is true
Note: This does not affect whether the validator succeeds or fails
func (*ValidatorContext) ClearCondition ¶
func (vc *ValidatorContext) ClearCondition(condition string)
ClearCondition clears a specified condition (token)
func (*ValidatorContext) ClearGlobalCondition ¶
func (vc *ValidatorContext) ClearGlobalCondition(condition string)
ClearGlobalCondition clears a specified condition (token) on the parent in the object tree
func (*ValidatorContext) ClearParentCondition ¶
func (vc *ValidatorContext) ClearParentCondition(condition string)
ClearParentCondition clears a specified condition (token) on the parent in the object tree
func (*ValidatorContext) CurrentArrayIndex ¶
func (vc *ValidatorContext) CurrentArrayIndex() *int
CurrentArrayIndex returns the current array index (or nil if current is a property name)
func (*ValidatorContext) CurrentDepth ¶
func (vc *ValidatorContext) CurrentDepth() int
CurrentDepth returns the current depth of the context - i.e. how many properties deep in the tree
func (*ValidatorContext) CurrentPath ¶
func (vc *ValidatorContext) CurrentPath() string
CurrentPath returns the current property path
func (*ValidatorContext) CurrentProperty ¶
func (vc *ValidatorContext) CurrentProperty() interface{}
CurrentProperty returns the current property - which may be a string (for property name) or an int (for array index)
Alternatively, to obtain the current property name use...
CurrentPropertyName
or the current array index use...
CurrentArrayIndex
func (*ValidatorContext) CurrentPropertyName ¶
func (vc *ValidatorContext) CurrentPropertyName() *string
CurrentPropertyName returns the current property name (or nil if current is an array index)
func (*ValidatorContext) CurrentValue ¶
func (vc *ValidatorContext) CurrentValue() interface{}
CurrentValue returns the current property value
func (*ValidatorContext) IsCondition ¶
func (vc *ValidatorContext) IsCondition(condition string) bool
IsCondition checks whether a specified condition (token) has been set
func (*ValidatorContext) Language ¶
func (vc *ValidatorContext) Language() string
Language implements I18nContext.Language (and relays it to internal i18nContext)
func (*ValidatorContext) Lock ¶
func (vc *ValidatorContext) Lock()
func (*ValidatorContext) Region ¶
func (vc *ValidatorContext) Region() string
Region implements I18nContext.Region (and relays it to internal i18nContext)
func (*ValidatorContext) SetCondition ¶
func (vc *ValidatorContext) SetCondition(condition string)
SetCondition sets a specified condition (token)
Note: if the condition (token) is prefixed with '!' then this is the same as calling ClearCondition
func (*ValidatorContext) SetGlobalCondition ¶
func (vc *ValidatorContext) SetGlobalCondition(condition string)
SetGlobalCondition sets a specified condition (token) for the entire validator context
Note: if the condition (token) is prefixed with '!' then this is the same as calling ClearGlobalCondition
func (*ValidatorContext) SetParentCondition ¶
func (vc *ValidatorContext) SetParentCondition(condition string)
SetParentCondition sets a specified condition (token) on the parent in the object tree
Note: if the condition (token) is prefixed with '!' then this is the same as calling ClearParentCondition
func (*ValidatorContext) Stop ¶
func (vc *ValidatorContext) Stop()
Stop causes the entire validation to stop - i.e. not further constraints or property value validations are performed
Note: This does not affect whether the validator succeeds or fails
func (*ValidatorContext) TranslateFormat ¶
func (vc *ValidatorContext) TranslateFormat(format string, a ...interface{}) string
TranslateFormat implements I18nContext.TranslateFormat (and relays it to internal i18nContext)
func (*ValidatorContext) TranslateMessage ¶
func (vc *ValidatorContext) TranslateMessage(msg string) string
TranslateMessage implements I18nContext.TranslateMessage (and relays it to internal i18nContext)
func (*ValidatorContext) TranslateToken ¶
func (vc *ValidatorContext) TranslateToken(token string) string
TranslateToken implements I18nContext.TranslateToken (and relays it to internal i18nContext)
func (*ValidatorContext) UnLock ¶
func (vc *ValidatorContext) UnLock()
func (*ValidatorContext) ValuesAncestry ¶
func (vc *ValidatorContext) ValuesAncestry() []interface{}
ValuesAncestry returns the values ancestry (where the first item is parent, second is grandparent etc.)
type ValidatorForOptions ¶
type ValidatorForOptions struct {
// IgnoreUnknownProperties is whether to ignore unknown properties (default false)
//
// Set this to `true` if you want to allow unknown properties
IgnoreUnknownProperties bool
// Constraints is an optional slice of Constraint items to be checked on the object/array
//
// * These are checked in the order specified and prior to property validator & unknown property checks
Constraints Constraints
// AllowNullJson forces validator to accept a request body that is null JSON (i.e. a body containing just `null`)
AllowNullJson bool
// AllowArray denotes, when true (default is false), that this validator will allow a JSON array - where each
// item in the array can be validated as an object
AllowArray bool
// DisallowObject denotes, when set to true, that this validator will disallow JSON objects - i.e. that it
// expects JSON arrays (in which case the AllowArray should also be set to true)
DisallowObject bool
// StopOnFirst if set, instructs the validator to stop at the first violation found
StopOnFirst bool
// UseNumber forces RequestValidate method to use json.Number when decoding request body
UseNumber bool
// OrderedPropertyChecks determines whether properties should be checked in order - when set to true, properties
// are sorted by PropertyValidator.Order and property name
//
// When this is set to false (default) properties are checked in the order in which they appear in the properties map -
// which is unpredictable
OrderedPropertyChecks bool
// OasInfo is additional information (for OpenAPI Specification)
OasInfo *OasInfo
}
ValidatorForOptions is used by ValidatorFor and MustCompileValidatorFor to set the initial overall validator for the struct
Note: This struct is not deprecated, but is retained for backward compatibility - it is now easier to use individual Option's when using ValidatorFor()
func (*ValidatorForOptions) Apply ¶
func (o *ValidatorForOptions) Apply(on *Validator) error
type VariablePropertyConstraint ¶
type VariablePropertyConstraint struct {
// NameConstraints is a slice of Constraint items that are checked against the property name
NameConstraints Constraints
// ObjectValidator is the Validator to use for the property value
ObjectValidator *Validator
// AllowNull when set to true, allows property values to be null (and not checked against the ObjectValidator)
AllowNull bool
}
VariablePropertyConstraint is a special constraint that allows properties with varying names to be validated
For example, if the following JSON needs to be validated:
{
"FOO": {
"amount": 123
},
"BAR": {
"amount": 345
}
}
but the property names "FOO" and "BAR" could be anything - then the following validator would work:
validator := &valix.Validator{
IgnoreUnknownProperties: true, // Important!
Constraints: Constraints{
&VariablePropertyConstraint{
ObjectValidator: &Validator{
Properties: valix.Properties{
"amount": {
Type: valix.JsonInteger,
Mandatory: true,
NotNull: true,
},
},
},
},
},
}
func (*VariablePropertyConstraint) Check ¶
func (c *VariablePropertyConstraint) Check(v interface{}, vcx *ValidatorContext) (bool, string)
func (*VariablePropertyConstraint) GetMessage ¶
func (c *VariablePropertyConstraint) GetMessage(tcx I18nContext) string
type Violation ¶
type Violation struct {
// Property is the name of the property that failed validation
Property string `json:"property"`
// Path is the path to the property that failed validation (in JSON format, e.g. "foo.bar[0].baz")
Path string `json:"path"`
// Message is the violation message
Message string `json:"message"`
// BadRequest is a flag indicating that the request could not be validated because
// the payload was not JSON. This effectively allows the caller of validation to determine
// whether to respond with `400 Bad Request` or `422 Unprocessable Entity`
//
// Such violations are only added by the Validator.RequestValidate method where:
//
// * the request has an empty body
//
// * the request body does not parse (unmarshal) as JSON
//
// * the request body is JSON null (i.e. a request body containing just 'null') and the
// Validator.AllowNullJson is set to false
BadRequest bool `json:"-"`
// Codes is a slice of anything needed to codify the violation (and can also be used to provide
// additional information about the violation)
Codes []interface{} `json:"-"`
}
Violation contains information about an encountered validation violation
func NewBadRequestViolation ¶
NewBadRequestViolation creates a new violation with BadRequest flag set (path and property are blank)
func NewEmptyViolation ¶
NewEmptyViolation creates a new violation with the specified message (path and property are blank)
Source Files
¶
- cloning.go
- constraint.go
- constraint_registry.go
- constraint_utils.go
- constraints_arr_obj.go
- constraints_compare.go
- constraints_datetime.go
- constraints_misc.go
- constraints_net.go
- constraints_number.go
- constraints_special.go
- constraints_string.go
- context.go
- doc.go
- i18n.go
- i18n_translations.go
- marshaling.go
- oas.go
- pattern_presets.go
- properties_expression.go
- properties_repo.go
- property_validator.go
- property_validator_tov8n.go
- providers.go
- query_validate.go
- tag_parsing.go
- tag_parsing_ops.go
- tags_extend.go
- unmarshaling.go
- utils.go
- utils_iso_codes.go
- utils_net.go
- validator.go
- validator_for.go
- validator_options.go
- violation.go