valix

package module
v1.13.1 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2023 License: Apache-2.0 Imports: 25 Imported by: 0

README

Valix

GoDoc Latest Version codecov Go Report Card Maintainability

Valix - Go package for validating requests

Contents

Overview

Validate JSON requests in the form of *http.Request, map[string]interface{} or []interface{}

Installation

To install Valix, use go get:

go get github.com/marrow16/valix

To update Valix to the latest version, run:

go get -u github.com/marrow16/valix

Features

  • Deep validation (define validation for properties where those properties are objects or arrays of objects that also need validating)
  • Create validators from structs or define them as code (see Creating Validators)
  • Validate http.Request (into struct or map[string]interface{})
  • Finds all validation violations - not just the first one! (see Using Validators) and provides information for each violation (property name, path and message)
  • Rich set of pre-defined common constraints (see Common Constraints)
  • Customisable constraints (see Custom Constraints)
  • Conditional constraints to support partial polymorphic request models (see Conditional Constraints)
  • Full Polymorphic Validation
  • Support for i18n - enabling translation of validation messages (inc. http.Request language and region detection)
  • Validators fully marshalable and unmarshalable (save/share validators as JSON)
  • Highly extensible (add your own constraints, messages, presets etc. without a PR to this repository)
  • 100% tested (see Codecov.io)
  • Coming soon - generate validators from OpenApi/Swagger JSON

Concepts

Valix is based on the concept that incoming API requests (such as POST, PUT etc.) should be validated early - against a definition of what the request body should look like.

At validation (of a JSON object as example) the following steps are performed:

  • Optionally check any constraints on the overall object (specified in Validator.Constraints)
  • Check if there are any unknown properties (unless Validator.IgnoreUnknownProperties is set to true)
  • For each defined property in Validator.Properties:
    • Check the property is present (if PropertyValidator.Mandatory is set to true)
    • Check the property value is non-null (if PropertyValidator.NotNull is set to true)
    • Check the property value is of the correct type (if PropertyValidator.Type is set)
    • Check the property value against constraints (specified in PropertyValidator.Constraints)
    • If the property value is an object or array (and PropertyValidator.ObjectValidator is specified) - check the value using the validator (see top of this process)

The validator does not stop on the first problem it finds - it finds all problems and returns them as a list (slice) of 'violations'. Each violation has a message along with the name and path of the property that failed. However, custom constraints can be defined that will either stop the entire validation or cease further validation constraints on the current property

Examples

Creating Validators

Validators can be created from existing structs - adding v8n tags (in conjunction with existing json tags), for example:

package main

import (
    "github.com/marrow16/valix"
)

type AddPersonRequest struct {
    Name string `json:"name" v8n:"notNull,mandatory,constraints:[StringNoControlCharacters{},StringLength{Minimum: 1, Maximum: 255}]"`
    Age int `json:"age" v8n:"type:Integer,notNull,mandatory,constraint:PositiveOrZero{}"`
}
var AddPersonRequestValidator = valix.MustCompileValidatorFor(AddPersonRequest{}, nil)

(see Validation Tags for documentation on v8n tags)

Or in slightly more abbreviated form (using & to denote constraint tokens):

package main

import (
    "github.com/marrow16/valix"
)

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)

The valix.MustCompileValidatorFor() function panics if the validator cannot be compiled. If you do not want a panic but would rather see the compilation error instead then use the valix.ValidatorFor() function instead.

Alternatively, Validators can be expressed effectively without a struct, for example:

package main

import (
    "github.com/marrow16/valix"
)

var CreatePersonRequestValidator = &valix.Validator{
    IgnoreUnknownProperties: false,
    Properties: valix.Properties{
        "name": {
            Type:         valix.JsonString,
            NotNull:      true,
            Mandatory:    true,
            Constraints:  valix.Constraints{
                &valix.StringNoControlCharacters{},
                &valix.StringLength{Minimum: 1, Maximum: 255},
            },
        },
        "age": {
            Type:         valix.JsonInteger,
            NotNull:      true,
            Mandatory:    true,
            Constraints:  valix.Constraints{
                &valix.PositiveOrZero{},
            },
        },
    },
}
Additional validator options

Validators can have additional properties that control the overall validation behaviour. These properties are described as follows:

Property Description
AllowArray (default false) Allows the validator to accept JSON arrays - and validate each item in the array
Setting this option to true whilst leaving the DisallowObject option as false means that the validator will accept either a JSON array or object
AllowNullJson Normally, a validator sees Null JSON (i.e. JSON string just containing the word null) as a violation - as it represents neither an object nor an array.
Setting this option to true disables this behaviour (and results of successful validation may return a nil map/slice)
NB. This option is only used by top-level validators
DisallowObject (default false) Prevents the validator from accepting JSON objects
Should only be set to true when AllowArray is also set to true
IgnoreUnknownProperties Normally, a validator will report as a violation any properties not defined within the validator
Setting this option to true means the validator will not check for unknown properties
OrderedPropertyChecks Normally, a validator checks specified properties in an unpredictable order (as they are stored in a map).
Setting this option to true means that the validator will check properties in order - by their Order field (or order tag) and then by name
StopOnFirst Normally, a validator will find all constraint violations
Setting this option to true causes the validator to stop when it finds the first violation
NB. This option is only used by top-level validators
UseNumber Validators use json.NewDecoder() to decode JSON
Setting this option to true instructs the validator to call Decoder.UseNumber() prior to decoding
NB. This option is only used by top-level validators
Using Validators

Once a validator has been created (using previous examples in Creating Validators), they can be used in several ways:

Validating a request into a struct

A request *http.Request can be validated into a struct:

package main

import (
    "encoding/json"
    "net/http"

    "github.com/marrow16/valix"
)

func AddPersonHandler(w http.ResponseWriter, r *http.Request) {
    addPersonReq := &AddPersonRequest{}
    ok, violations, _ := CreatePersonRequestValidator.RequestValidateInto(r, addPersonReq)
    if !ok {
        // write an error response with full info - using violations information
        valix.SortViolationsByPathAndProperty(violations)
        errResponse := map[string]interface{}{
            "$error": "Request invalid",
            "$details": violations,
        }
        w.WriteHeader(http.StatusUnprocessableEntity)
        w.Header().Set("Content-Type", "application/json")
        _ = json.NewEncoder(w).Encode(errResponse)
        return
    }
    // the addPersonReq will now be a validated struct
    w.Header().Set("Content-Type", "application/json")
    _ = json.NewEncoder(w).Encode(addPersonReq)
}
Validating a string or reader into a struct

A string, representing JSON, can be validated into a struct:

package main

import (
    "testing"

    "github.com/marrow16/valix"
    "github.com/stretchr/testify/require"
)

func TestValidateStringIntoStruct(t *testing.T) {
    str := `{
        "name": "",
        "age": -1
    }`
    req := &AddPersonRequest{}
    ok, violations, _ := AddPersonRequestValidator.ValidateStringInto(str, req)
    
    require.False(t, ok)
    require.Equal(t, 2, len(violations))
    valix.SortViolationsByPathAndProperty(violations)
    require.Equal(t, "Value must be positive or zero", violations[0].Message)
    require.Equal(t, "age", violations[0].Property)
    require.Equal(t, "", violations[0].Path)
    require.Equal(t, "String value length must be between 1 and 255 (inclusive)", violations[1].Message)
    require.Equal(t, "name", violations[1].Property)
    require.Equal(t, "", violations[1].Path)
    
    str = `{
        "name": "Bilbo Baggins",
        "age": 25
    }`
    ok, violations, _ = AddPersonRequestValidator.ValidateStringInto(str, req)
    
    require.True(t, ok)
    require.Equal(t, 0, len(violations))
    require.Equal(t, "Bilbo Baggins", req.Name)
    require.Equal(t, 25, req.Age)
}

Also, a reader io.Reader can be validated into a struct using the .ValidateReaderIntoStruct() method of the validator:

package main

import (
    "strings"
    "testing"

    "github.com/marrow16/valix"
    "github.com/stretchr/testify/require"
)

func TestValidateReaderIntoStruct(t *testing.T) {
	reader := strings.NewReader(`{
		"name": "",
		"age": -1
	}`)
	req := &AddPersonRequest{}

	ok, violations, _ := AddPersonRequestValidator.ValidateReaderInto(reader, req)

	require.False(t, ok)
	require.Equal(t, 2, len(violations))
	valix.SortViolationsByPathAndProperty(violations)
	require.Equal(t, "Value must be positive or zero", violations[0].Message)
	require.Equal(t, "age", violations[0].Property)
	require.Equal(t, "", violations[0].Path)
	require.Equal(t, "String value length must be between 1 and 255 (inclusive)", violations[1].Message)
	require.Equal(t, "name", violations[1].Property)
	require.Equal(t, "", violations[1].Path)

	reader = strings.NewReader(`{
		"name": "Bilbo Baggins",
		"age": 25
	}`)
	ok, violations, _ = AddPersonRequestValidator.ValidateReaderInto(reader, req)

	require.True(t, ok)
	require.Equal(t, 0, len(violations))
	require.Equal(t, "Bilbo Baggins", req.Name)
	require.Equal(t, 25, req.Age)
}
Validating a map

Validators can also validate a map[string]interface{} representation of a JSON object:

package main

import (
    "testing"

    "github.com/marrow16/valix"
    "github.com/stretchr/testify/require"
)

func TestValidateMap(t *testing.T) {
    req := map[string]interface{}{
        "name": "",
        "age": -1,
    }
  
    ok, violations := AddPersonRequestValidator.Validate(req)
    require.False(t, ok)
    require.Equal(t, 2, len(violations))
    valix.SortViolationsByPathAndProperty(violations)
    require.Equal(t, "Value must be positive or zero", violations[0].Message)
    require.Equal(t, "age", violations[0].Property)
    require.Equal(t, "", violations[0].Path)
    require.Equal(t, "String value length must be between 1 and 255 (inclusive)", violations[1].Message)
    require.Equal(t, "name", violations[1].Property)
    require.Equal(t, "", violations[1].Path)
  
    req = map[string]interface{}{
        "name": "Bilbo Baggins",
        "age": 25,
    }
    ok, _ = AddPersonRequestValidator.Validate(req)
    require.True(t, ok)
}
Validating a slice

Validators can also validate a slice []interface{} representation of a JSON object, where each object element in the slice is validated:

package main

import (
    "testing"

    "github.com/marrow16/valix"
    "github.com/stretchr/testify/require"
)

func TestValidateSlice(t *testing.T) {
    req := []interface{}{
        map[string]interface{}{
            "name": "",
            "age":  -1,
        },
        map[string]interface{}{
            "name": "Bilbo Baggins",
            "age":  25,
        },
    }
  
    ok, violations := AddPersonRequestValidator.ValidateArrayOf(req)
    require.False(t, ok)
    require.Equal(t, 2, len(violations))
    valix.SortViolationsByPathAndProperty(violations)
    require.Equal(t, "Value must be positive or zero", violations[0].Message)
    require.Equal(t, "age", violations[0].Property)
    require.Equal(t, "[0]", violations[0].Path)
    require.Equal(t, "String value length must be between 1 and 255 (inclusive)", violations[1].Message)
    require.Equal(t, "name", violations[1].Property)
    require.Equal(t, "[0]", violations[1].Path)
  
    req = []interface{}{
        map[string]interface{}{
            "name": "Frodo Baggins",
            "age":  20,
        },
        map[string]interface{}{
            "name": "Bilbo Baggins",
            "age":  25,
        },
    }
    ok, _ = AddPersonRequestValidator.ValidateArrayOf(req)
    require.True(t, ok)
}

Constraints

In Valix, a constraint is a particular validation rule that must be satisfied. For a constraint to be used by the validator it must implement the valix.Constraint interface.

Common Constraints

Valix provides a rich set of over 100 pre-defined common constraints (plus many common regex patterns) - see Constraints Reference wiki documentation for full reference with examples.

Constraint Sets

It is not uncommon in APIs for many properties in different requests to share a common set of constraints. For this reason, Valix provides a ConstraintSet - which is itself a Constraint but contains a list of sub-constraints.

type ConstraintSet struct {
    Constraints Constraints
    Message string
}

When checking a ConstraintSet, the contained constraints are checked sequentially but the overall set stops on the first failing constraint.

If a Message is provided (non-empty string) then that message is used for any of the failing constraints - otherwise the individual constraint fail messages are used.

The following is an example of a constraint set which imposes a complex constraint (although one that could probably be more easily achieved using valix.StringPattern)

package main

import (
    "unicode"
    "github.com/marrow16/valix"
)

var MySet = &valix.ConstraintSet{
    Constraints: valix.Constraints{
        &valix.StringTrim{},
        &valix.StringNotEmpty{},
        &valix.StringLength{Minimum: 16, Maximum: 64},
        valix.NewCustomConstraint(func(value interface{}, vcx *valix.ValidatorContext, this *valix.CustomConstraint) (bool, string) {
            if str, ok := value.(string); ok {
                if len(str) == 0 || str[0] < 'A' || str[0] > 'Z' {
                    return false, this.GetMessage(vcx)
                }
            }
            return true, ""
        }, ""),
        &valix.StringCharacters{
            AllowRanges: []unicode.RangeTable{
                {R16: []unicode.Range16{{'0', 'z', 1}}},
            },
            DisallowRanges: []unicode.RangeTable{
                {R16: []unicode.Range16{{0x003a, 0x0040, 1}}},
                {R16: []unicode.Range16{{0x005b, 0x005e, 1}}},
                {R16: []unicode.Range16{{0x0060, 0x0060, 1}}},
            },
        },
    },
    Message: "String value length must be between 16 and 64 chars; must be letters (upper or lower), digits or underscores; must start with an uppercase letter",
}

Constraint sets can also be registered, making them available in v8n struct tags.

Custom Constraints

If you need a constraint for a specific domain validation, there are two ways to do this...

Create a re-usable constraint (which implements the valix.Constraint interface), example:

package main

import (
    "strings"
    "github.com/marrow16/valix"
)

type NoFoo struct {
}

func (c *NoFoo) Check(value interface{}, vcx *valix.ValidatorContext) (bool, string) {
    if str, ok := value.(string); ok {
        return !strings.Contains(str, "foo"), c.GetMessage(vcx)
    }
    return true, ""
}

func (c *NoFoo) GetMessage(tcx I18nContext) string {
    return "Value must not contain \"foo\""
}

Or create a custom constraint on the fly with check function, example:
Note: Custom constraints using functions means that the validator cannot be marshalled/unmarshalled

package main

import (
    "strings"
    "github.com/marrow16/valix"
)

var myValidator = &valix.Validator{
    IgnoreUnknownProperties: false,
    Properties: valix.Properties{
        "foo": {
            Type:         valix.JsonString,
            NotNull:      true,
            Mandatory:    true,
            Constraints:  valix.Constraints{
                valix.NewCustomConstraint(func(value interface{}, vcx *valix.ValidatorContext, cc *valix.CustomConstraint) (bool, string) {
                    if str, ok := value.(string); ok {
                        return !strings.Contains(str, "foo"), cc.GetMessage(vcx)
                    }
                    return true, ""
                }, "Value must not contain \"foo\""),
            },
        },
    },
}
Constraints Registry

All of the Valix common constraints are loaded into a registry - the registry enables the v8n tags to reference these.

If you want to make your own custom constraint available for use in v8n tags, it must also be registered. For example:

package main

import (
    "strings"
    "github.com/marrow16/valix"
)

func init() {
    valix.RegisterConstraint(&NoFoo{})
}

// and the constraint can now be used in `v8n` tag...
type MyRequest struct {
    Name string `json:"name" v8n:"&NoFoo{}"`
}
Required/Unwanted Properties

When properties are required, or unwanted, according to the presence of other properties - use the v8n tag tokens required_with:<expr> or unwanted_with:<expr> (abbreviated forms +: and -: respectively).

The simplest expression is just the name of another property - the following example shows making two properties foo and bar mutually inclusive (i.e. if one is present then the other is required):

type ExampleMutuallyInclusive struct {
    Foo string `json:"foo" v8n:"+:bar, +msg:'foo required when bar present'"`
    Bar string `json:"bar" v8n:"+:foo, +msg:'bar required when foo present'"`
}

Or another example, using the unwanted_with: token, to make two properties mutually exclusive (i.e. if one is present then the other must not):

type ExampleMutuallyExclusive struct {
    Foo string `json:"foo" v8n:"-:bar, -msg:'foo and bar are mutually exclusive'"`
    Bar string `json:"bar" v8n:"-:foo, -msg:'foo and bar are mutually exclusive'"`
}

The required_with: and unwanted_with can also use more complex boolean expressions - the following example demonstrates making two out of three properties mutually inclusive but not all three:

type ExampleTwoOfThreeMutuallyInclusive struct {
    Foo string `json:"foo" v8n:"+:(bar || baz) && !(bar && baz), -:bar && baz"`
    Bar string `json:"bar" v8n:"+:(foo || baz) && !(foo && baz), -:foo && baz"`
    Baz string `json:"baz" v8n:"+:(foo || bar) && !(foo && bar), -:foo && bar"`
}

The boolean property expressions can also traverse up and down the object tree (using JSON . path style notation). The following demonstrates:

type ExampleUpAndDownRequired struct {
    Foo string `json:"foo" v8n:"+:sub.foo"`
    Bar string `json:"bar" v8n:"+:sub.bar"`
    Sub struct {
        SubFoo string `json:"foo" v8n:"+:..foo"`
        SubBar string `json:"bar" v8n:"+:..bar"`
    } `json:"sub"`
}

Additional expression functionality notes:

  • Boolean operator ^^ (XOr) is also supported
  • Path traversal also supports going up to the root object - e.g. /.foo.bar will go up to the root object and then descend down path foo.bar
  • Prefixing property name with ~ (tilde) means check a context condition rather than property existence - e.g. ~METHOD_POST checks whether the METHOD_POST condition token has been set in the context
  • The +: and -: validation tag tokens correspond to the valix.PropertyValidator.RequiredWith and valix.PropertyValidator.UnwantedWith fields respectively
  • Use the valix.ParseExpression or valix.MustParseExpression functions to programmatically parse boolean property expressions
  • Unfortunately, array index notation (e.g. sub[0]) is not currently supported (and neither is traversing array values)
Conditional Constraints

Sometimes, the model of JSON requests needs to vary according to some property condition. For example, the following is a beverage order for a tea and coffee shop:

type BeverageOrder struct {
    Type     string `json:"type" v8n:"notNull,required,&StringValidToken{Tokens:['tea','coffee']}"`
    Quantity int    `json:"quantity" v8n:"notNull,required,&Positive{}"`
    // only relevant to type="tea"...
    Blend    string `json:"blend" v8n:"notNull,required,&StringValidToken{Tokens:['Earl Grey','English Breakfast','Masala Chai']}"`
    // only relevant to type="coffee"...
    Roast    string `json:"roast" v8n:"notNull,required,&StringValidToken{Tokens:['light','medium','dark']}"`
}

The above validation will always expect the blend and roast properties to be present and their value to be valid. However, this is not the requirement of the model - we only want:

  • the blend property to be present and valid when type="tea"
  • the 'roast' property to be present and valid when type="coffee"

These validation requirements can be incorporated by using the 'when conditions':

type BeverageOrder struct {
    Type     string `json:"type" v8n:"notNull,required,order:-1,&StringValidToken{Tokens:['tea','coffee']},&SetConditionFrom{Parent:true}"`
    Quantity int    `json:"quantity" v8n:"notNull,required,&Positive{}"`
    // only relevant to type="tea"...
    Blend    string `json:"blend" v8n:"when:tea,notNull,required,&StringValidToken{Tokens:['Earl Grey','English Breakfast','Masala Chai']}"`
    // only relevant to type="coffee"...
    Roast    string `json:"roast" v8n:"when:coffee,notNull,required,&StringValidToken{Tokens:['light','medium','dark']}"`
}

Note in the above:

  • on the Type field:
    • order:-1 means that this property is checked
    • &SetConditionFrom{} sets a validator context condition token from the incoming value of property type
      therefore, either a validator condition token of tea or coffee will be set
      Note: the Parent:true means properties at the same level as this will see the condition token
  • on the Blend field the when:tea tag has been added - which means the blend property is only checked when there is a validator condition token of tea set
  • on the Roast field the when:coffee tag has been added - which means the roast property is only checked when there is a validator condition token of coffee set

However, this second example may still not be strict enough - because it allows the blend property to be present when the type is "coffee" and the roast property to be present when the type is "tea"
This can be overcome by using the 'unwanted conditions':

type BeverageOrderStrict struct {
    Type     string `json:"type" v8n:"notNull,required,order:-1,&StringValidToken{Tokens:['tea','coffee']},&SetConditionFrom{Parent:true}"`
    Quantity int    `json:"quantity" v8n:"notNull,required,&Positive{}"`
    // Blend is only relevant when type="tea"...
    Blend    string `json:"blend" v8n:"when:tea,unwanted:!tea,notNull,required,&StringValidToken{Tokens:['Earl Grey','English Breakfast','Masala Chai']}"`
    // Roast is only relevant when type="coffee"...
    Roast    string `json:"roast" v8n:"when:coffee,unwanted:!coffee,notNull,required,&StringValidToken{Tokens:['light','medium','dark']}"`
}

Note in the above:

  • the unwanted:!tea tag has been added to the Blend field - which means... "if condition token of tea has not been set then we do not want the blend property to be present"
  • the unwanted:!coffee tag has been added to the Roast field - which means... "if condition token of coffee has not been set then we do not want the roast property to be present"

Polymorphic Validation

Sometimes, the model of JSON requests needs to vary completely according to some condition. The previous conditional constraints example can solve some of the conditional variance - but when different properties are required/not-required or same properties have different constraints under different conditions then polymorphic validation becomes necessary.

As an example, if the following requests all need to be validated using a single validator:

{
    "type": "tea",
    "quantity": 1,
    "blend": "Earl Grey|English Breakfast|Masala Chai"
}
{
    "type": "coffee",
    "quantity": 1,
    "roast": "light|medium|dark"
}
{
    "type": "soft",
    "quantity": 1,
    "brand": "Coca Cola",
    "flavor": "Regular|Diet|Zero|Cherry"
}
{
    "type": "soft",
    "quantity": 1,
    "brand": "Tango",
    "flavor": "Orange|Apple|Strawberry|Watermelon|Tropical"
}

A demonstrated solution to this can be see in the Polymorphic example code

Note: Polymorphic validators cannot be derived from struct tags (see Validation Tags) - because structs themselves cannot be polymorphic!

Validation Tags

Valix can read tags from struct fields when building validators. These are the v8n tags, in the format:

type example struct {
    Field string `v8n:"token[,token, ...]"`
}

Where the tokens correspond to various property validation options - as listed here:

Token Purpose & Example
constraint:constraint-name{fields...} Adds a constraint to the property (this token can be specified multiple times within the v8n tag. The constraint-name must be a Valix common constraint or a previously registered constraint. The constraint `fields` can optionally be set.
Example
type Example struct {
  Foo string `v8n:"constraint:StringMaxLength{Value:255}"`
}
constraints:[constraint-name{},...] Adds multiple constraints to the property
Example
type Example struct {
  Foo string `v8n:"constraints:[StringNotEmpty{},StringNoControlCharacters{}]"`
}
&constraint-name{fields...} Adds a constraint to the property (shorthand way of specifying constraint without constraint: or constraints:[] prefix)
Example
type Example struct {
  Foo string `v8n:"&StringMaxLength{Value:255}"`
}
&[condition,...]constraint-name{fields...} Adds a conditional constraint to the property - the constraint is only checked when the condition(s) are met
Example
type Example struct {
  Foo string `v8n:"&[METHOD_POST]StringNotEmpty{}"`
}
The StringNotEmpty constraint is only checked when the METHOD_POST condition token has been set
&<expr>constraint-name{fields...} Adds a conditional constraint to the property - the constraint is only checked when the expr evaluates to true
Example
type Example struct {
  Foo string `json:"foo" v8n:"&<(bar && !baz) || (!bar && baz)>StringNotEmpty{}"`
  Bar string `json:"bar" v8n:"optional"`
  Baz string `json:"baz" v8n:"optional"`
}
The StringNotEmpty constraint is only checked when only one of the bar or baz properties are present
mandatory Specifies the JSON property must be present
Example
type Example struct {
  Foo string `v8n:"mandatory"`
}
mandatory:condition
      or
mandatory:[condition,...]
Specifies the JSON property must be present under specified conditions
Example
type Example struct {
  Foo string `v8n:"mandatory:[METHOD_POST,METHOD_PATCH]"`
}
required_with:expr
      or
+:expr
Specifies the JSON property is required according to the presence/non-presence of other properties (as determined by the expr)
You can also control the violation message used when the property is required but missing using a required_with_msg: or +msg: tag token
Example
type Example struct {
  Foo string `json:"foo" v8n:"required_with:bar && baz,+msg:'Sometimes foo is required'"`
  Bar string `json:"bar"`
  Baz string `json:"baz"`
}
Means the property foo is required when both bar and baz properties are present
Use +msg or required_with_msg to alter the message used when this constraint fails

(see also Required/Unwanted Properties for further notes and examples on expressions)
unwanted_with:expr
      or
-:expr
Specifies the JSON property is unwanted according to the presence/non-presence of other properties (as determined by the expr)
You can also control the violation message used when the property is present but unwanted using a unwanted_with_msg: or -msg: tag token
Example
type Example struct {
  Foo string `json:"foo" v8n:"unwanted_with:bar || baz,-msg:'Sometimes foo is unwanted'"`
  Bar string `json:"bar"`
  Baz string `json:"baz"`
}
Means the property foo is unwanted when either the bar or baz properties are present
Use -msg or unwanted_with_msg to alter the message used when this constraint fails

(see also Required/Unwanted Properties for further notes and examples on expressions)
notNull Specifies the JSON value for the property cannot be null
Example
type Example struct {
  Foo string `v8n:"notNull"`
}
nullable Specifies the JSON value for the property can be null (opposite of notNull)
Example
type Example struct {
  Foo string `v8n:"nullable"`
}
optional Specifies the JSON property does not have to be present (opposite of mandatory)
Example
type Example struct {
  Foo string `v8n:"optional"`
}
order:n Specifies the order in which the property should be validated (only respected if parent object is tagged as obj.ordered or parent validator is set to OrderedPropertyChecks)
Example
type Example struct {
  Foo string `v8n:"order:0"`
  Bar string `v8n:"order:1"`
}
only
      or
only:condition
      or
only:[condition,...]
Specifies that the property must not be present with other properties
Example
type Example struct {
  Foo string `v8n:"only,mandatory"`
  Bar string `v8n:"only,mandatory"`
  Baz string `v8n:"only,mandatory"`
}
In the above example, a request with only one of the Foo, Bar or Baz will be valid - specifying more than one of those properties would cause a violation.
Note that even though all three properties are mandatory - if only one of the properties is present, then the other mandatories are ignored.
Use only_msg to alter the message used when this constraint fails
required same as mandatory
Example
type Example struct {
  Foo string `v8n:"required"`
}
required:condition
      or
required:[condition,...]
same as mandatory:condition
Example
type Example struct {
  Foo string `v8n:"required:[METHOD_POST,METHOD_PATCH]"`
}
stop_on_first
      or
stop1st
Specifies that property validation to stop at the first constraint violation found
Note: This would be the equivalent of setting Stop on each constraint
Example
type Example struct {
  Foo string `v8n:"stop_on_first,&StringNotBlank{},&StringNotEmpty{}"`
}
In the above example, only one of the specified constraints would fail
type:type Specifies (overrides) the type expected for the JSON property value
Where type must be one of (case-insensitive):
   string, number, integer, boolean, object, array or any
Example
type Example struct {
  Foo json.Number `v8n:"type:integer"`
}
when:condition
      or
when:[condition,...]
Adds when condition(s) for the property - where condition is a condition token (that may have been set during validation)
The property is only validated when these conditions are met (see Conditional Constraints)
Example
type Example struct {
  Foo string `v8n:"when:YES_FOO"`
}
unwanted:condition
      or
unwanted:[condition,...]
Adds unwanted condition(s) for the property - where condition is a condition token (that may have been set during validation)
If the unwanted condition(s) is met but the property is present then this is a validation violation (see Conditional Constraints)
Example
type Example struct {
  Foo string `v8n:"unwanted:NO_FOO"`
}
obj.ignoreUnknownProperties Sets an object (or array of objects) to ignore unknown properties (ignoring unknown properties means that the validator will not fail if an unknown property is found)
Example
type Example struct {
  SubObj struct{
    Foo string
  } `json:"subObj" v8n:"obj.ignoreUnknownProperties"`
}
obj.unknownProperties:true|false Sets whether an object is to allow/ignore (true) or disallow (false) unknown properties
Example
type Example struct {
  SubObj struct{
    Foo string
  } `json:"subObj" v8n:"obj.unknownProperties:false"`
}
obj.constraint:constraint-name{} Sets a constraint on an entire object or array
Example
type Example struct {
  SubObj struct{
    Foo string
  } `json:"subObj" v8n:"obj.constraint:Length{Minimum:1,Maximum:16}"`
}
obj.ordered Sets the object validator to check properties in order
(same as Validator.OrderedPropertyChecks in Additional validator options)
Example
type Example struct {
  SubObj struct{
    Foo string `v8n:"order:0"`
    Bar string `v8n:"order:1"`
  } `v8n:"obj.ordered"`
}
the above will check the properties in order specified by their order: - whereas the following will check the properties in alphabetical order of name...
type Example struct {
  SubObj struct{
    Foo string `json:"foo"`
    Bar string `json:"bar"`
  } `v8n:"obj.ordered"`
}
obj.when:condition
      or
obj.when:[condition,...]
Adds when condition(s) for the object or array - where condition is a condition token (that may have been set during validation)
The object/array is only validated when these conditions are met (see Conditional Constraints)
Example
type Example struct {
  SubObj struct{
    Foo string
  } `json:"subObj" v8n:"obj.when:YES_SUB"`
}
arr.allowNulls
For array (slice) fields, specifies that array elements can be null
Example
type Example struct {
  SubSlice []*struct {
    Foo string
  } `json:"subSlice" v8n:"arr.allowNulls"`
}
Registering your own tag tokens

The v8n tag can also support custom tokens which can be registered using valix.RegisterCustomTagToken. Any registered custom tag tokens can be used in the v8n tag and will be processed when building a validator for a struct using valix.ValidatorFor

An example of how this is used can be found in examples/custom_tag_tokens_test.go

Tag token aliases

If you find that you're using the same v8n tag tokens repeatedly - you can create aliases for these and then just reference the alias using a $ prefix.

An example of how this is used can be found in examples/tag_aliases_test.go

Abbreviating constraints in tags

When specifying constraints in tags, especially with constraint args, the struct tags can become a little verbose. For example:

type MyStruct struct {
    Foo string `json:"foo" v8n:"&StringNoControlCharacters{},&StringUppercase{Message:'Upper only'},&StringLength{Minimum:10,Maximum:20,ExclusiveMin:true}"`
}

To overcome this, there are several things you can do:

  1. Where there are no args for the constraint, the {} at the end can be dropped
  2. Where the constraint struct has only one field or has a default field (tagged with `v8n:"default"`) then the arg name can be dropped
  3. The constraints registry has pre-defined abbreviated forms
  4. Constraint arg names can be abbreviated or shortened to closest matching name, e.g.
    1. Message can be abbreviated to Msg or msg (case-insensitive, remove vowels, replace double-characters with single)
    2. Minimum can be shortened to Min or min (or any other variation that matches only one target field name)
    3. ExclusiveMin can be shortened to excMin, exMin, eMin etc.
  5. Where a constraint field is a bool and setting it to true - the value (:true) can be omitted

After those steps, the constraint tags would be:

type MyStruct struct {
    Foo string `json:"foo" v8n:"&strnocc,&strupper{'Upper only'},&strlen{stp,min:10,max:20,excMin}"`
}

Internationalisation Support

Valix has full I18n support for translating violation messages - which is both extensible and/or replaceable...

I18n support features:
  • Support for both language and region (e.g. en, en-GB, en-US, fr and fr-CA etc.)
  • Detection of request Accept-Language header
    (when using Validator.RequestValidate or Validator.RequestValidateInto)
  • Fallback language and region support
    • e.g. if fr-CA was requested but no Canadian specific translation then fr is used
    • e.g. if mt (Maltese) is an unsupported language but you want the fallback language to be it (Italian) then set this in the valix.DefaultFallbackLanguages variable, e.g. valix.DefaultFallbackLanguages["mt"] = "it"
  • Default runtime language and region changeable
    (set vars valix.DefaultLanguage and/or valix.DefaultRegion)
  • Built-in valix.DefaultTranslator supports English, French, German, Italian and Spanish
    • more languages and regional variants can be added at runtime
    • replace translator with your own (implementing valix.Translator interface)
  • Completely replaceable I18n support (replace variable valix.DefaultI18nProvider with your own)

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

View Source
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"
)
View Source
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
)
View Source
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
)
View Source
const (
	ISO4217TestCurrencyCode        = "XTS"
	ISO4217TestCurrencyCodeNumeric = "963"
	ISO4217NoCurrencyCode          = "XXX"
	ISO4217NoCurrencyCodeNumeric   = "999"
)
View Source
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
)
View Source
const (
	// NoMessage is a special message used by constraints to indicate no message rather than default message
	NoMessage = "[NO_MESSAGE]"
)

Variables

View Source
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},
		},
	}
)
View Source
var DefaultFallbackLanguages = map[string]string{}

DefaultFallbackLanguages is a map of language codes with their fallback language code

View Source
var DefaultLanguage = "en"

DefaultLanguage is the default language used by the default I18nProvider

Languages provided are "de", "en", "es", "fr" & "it"

View Source
var DefaultRegion = ""

DefaultRegion is the default region used by the default I18nProvider

Functions

func ClearCustomTagTokens added in v1.9.0

func ClearCustomTagTokens()

ClearCustomTagTokens clears any custom tag tokens registered using RegisterCustomTagToken

func ClearCustomTags added in v1.9.0

func ClearCustomTags()

ClearCustomTags clears any registered custom tags that were registered using RegisterCustomTag

func ClearTagTokenAliases added in v1.9.0

func ClearTagTokenAliases()

ClearTagTokenAliases clears any tag aliases registered using RegisterTagTokenAlias / RegisterTagTokenAliases

func ConstraintsRegistryHas added in v1.5.0

func ConstraintsRegistryHas(name string) bool

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 added in v1.5.0

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 added in v1.9.0

func PropertiesRepoClear()

PropertiesRepoClear clears the properties repository

func PropertiesRepoPanics added in v1.9.0

func PropertiesRepoPanics(panics bool)

PropertiesRepoPanics sets whether the properties repository panics when asked for a common property that does not exist

func ReRegisterConstraint added in v1.6.2

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 added in v1.6.2

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 added in v1.6.2

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 added in v1.6.2

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 added in v1.5.0

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 added in v1.5.0

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 added in v1.9.0

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 added in v1.9.0

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 added in v1.5.0

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 added in v1.5.0

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 added in v1.8.2

func RegisterPreset(token string, preset Preset, asConstraint bool)

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 added in v1.8.0

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 added in v1.9.0

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 added in v1.9.0

func RegisterTagTokenAlias(alias string, val string)

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 added in v1.9.0

func RegisterTagTokenAliases(aliases TagAliases)

RegisterTagTokenAliases register multiple tag aliases - see RegisterTagTokenAlias

func SortViolationsByPathAndProperty added in v1.5.1

func SortViolationsByPathAndProperty(violations []*Violation)

SortViolationsByPathAndProperty is a utility function for sorting violations

Types

type ArrayConditionalConstraint added in v1.9.9

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 added in v1.9.9

func (c *ArrayConditionalConstraint) Check(v interface{}, vcx *ValidatorContext) (bool, string)

func (*ArrayConditionalConstraint) GetMessage added in v1.9.9

func (c *ArrayConditionalConstraint) GetMessage(tcx I18nContext) string

func (*ArrayConditionalConstraint) MarshalJSON added in v1.9.9

func (c *ArrayConditionalConstraint) MarshalJSON() ([]byte, error)

func (*ArrayConditionalConstraint) UnmarshalJSON added in v1.9.9

func (c *ArrayConditionalConstraint) UnmarshalJSON(data []byte) error

type ArrayDistinctProperty added in v1.10.11

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 added in v1.10.11

func (c *ArrayDistinctProperty) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*ArrayDistinctProperty) GetMessage added in v1.10.11

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 added in v1.8.0

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 added in v1.8.0

func (c *ArrayUnique) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*ArrayUnique) GetMessage added in v1.8.0

func (c *ArrayUnique) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type BooleanOperator added in v1.9.0

type BooleanOperator int
const (
	And BooleanOperator = iota
	Or
	Xor
)

type Check

type Check func(value interface{}, vcx *ValidatorContext, this *CustomConstraint) (passed bool, message string)

Check function signature for custom constraints

type Conditional added in v1.12.0

type Conditional interface {
	MeetsConditions(vcx *ValidatorContext) bool
}

type ConditionalConstraint added in v1.8.1

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 added in v1.8.1

func (c *ConditionalConstraint) Check(v interface{}, vcx *ValidatorContext) (bool, string)

func (*ConditionalConstraint) GetMessage added in v1.8.1

func (c *ConditionalConstraint) GetMessage(tcx I18nContext) string

func (*ConditionalConstraint) MeetsConditions added in v1.12.0

func (c *ConditionalConstraint) MeetsConditions(vcx *ValidatorContext) bool

type ConditionalVariant added in v1.8.0

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 added in v1.9.0

func (src *ConditionalVariant) Clone() *ConditionalVariant

type ConditionalVariants added in v1.8.0

type ConditionalVariants []*ConditionalVariant

ConditionalVariants type used by Validator.ConditionalVariants

func (ConditionalVariants) Clone added in v1.9.0

type Conditions added in v1.8.1

type Conditions []string

func (Conditions) Clone added in v1.9.0

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 added in v1.8.2

func GetRegisteredConstraint(name string) (Constraint, bool)

GetRegisteredConstraint returns a previously registered constraint

type ConstraintSet added in v1.0.2

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 added in v1.0.2

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 added in v1.0.2

func (c *ConstraintSet) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

func (*ConstraintSet) MarshalJSON added in v1.8.0

func (c *ConstraintSet) MarshalJSON() ([]byte, error)

func (*ConstraintSet) UnmarshalJSON added in v1.8.0

func (c *ConstraintSet) UnmarshalJSON(data []byte) error

type Constraints

type Constraints []Constraint

Constraints type used by Validator.Constraints and PropertyValidator.Constraints

func (Constraints) Clone added in v1.9.0

func (src Constraints) Clone() Constraints

func (Constraints) MarshalJSON added in v1.8.0

func (cs Constraints) MarshalJSON() ([]byte, error)

func (*Constraints) UnmarshalJSON added in v1.8.0

func (cs *Constraints) UnmarshalJSON(data []byte) error

type CustomConstraint

type CustomConstraint struct {
	CheckFunc Check
	Message   string
}

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 added in v1.9.0

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 added in v1.10.6

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 added in v1.10.6

func (c *DatetimeDayOfWeek) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*DatetimeDayOfWeek) GetMessage added in v1.10.6

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 added in v1.8.0

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 added in v1.8.0

func (c *DatetimeGreaterThan) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*DatetimeGreaterThan) GetMessage added in v1.8.0

func (c *DatetimeGreaterThan) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type DatetimeGreaterThanOrEqual added in v1.8.0

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 added in v1.8.0

func (c *DatetimeGreaterThanOrEqual) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*DatetimeGreaterThanOrEqual) GetMessage added in v1.8.0

func (c *DatetimeGreaterThanOrEqual) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type DatetimeGreaterThanOrEqualOther added in v1.8.0

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 added in v1.8.0

func (c *DatetimeGreaterThanOrEqualOther) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*DatetimeGreaterThanOrEqualOther) GetMessage added in v1.8.0

GetMessage implements the Constraint.GetMessage

type DatetimeGreaterThanOther added in v1.8.0

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 added in v1.8.0

func (c *DatetimeGreaterThanOther) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*DatetimeGreaterThanOther) GetMessage added in v1.8.0

func (c *DatetimeGreaterThanOther) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type DatetimeLessThan added in v1.8.0

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 added in v1.8.0

func (c *DatetimeLessThan) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*DatetimeLessThan) GetMessage added in v1.8.0

func (c *DatetimeLessThan) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type DatetimeLessThanOrEqual added in v1.8.0

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 added in v1.8.0

func (c *DatetimeLessThanOrEqual) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*DatetimeLessThanOrEqual) GetMessage added in v1.8.0

func (c *DatetimeLessThanOrEqual) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type DatetimeLessThanOrEqualOther added in v1.8.0

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 added in v1.8.0

func (c *DatetimeLessThanOrEqualOther) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*DatetimeLessThanOrEqualOther) GetMessage added in v1.8.0

func (c *DatetimeLessThanOrEqualOther) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type DatetimeLessThanOther added in v1.8.0

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 added in v1.8.0

func (c *DatetimeLessThanOther) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*DatetimeLessThanOther) GetMessage added in v1.8.0

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 added in v1.10.8

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 added in v1.10.8

func (c *DatetimeRange) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*DatetimeRange) GetMessage added in v1.10.8

func (c *DatetimeRange) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type DatetimeTimeOfDayRange added in v1.10.8

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 added in v1.10.8

func (c *DatetimeTimeOfDayRange) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*DatetimeTimeOfDayRange) GetMessage added in v1.10.8

func (c *DatetimeTimeOfDayRange) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type DatetimeTolerance added in v1.8.0

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 added in v1.8.0

func (c *DatetimeTolerance) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*DatetimeTolerance) GetMessage added in v1.8.0

func (c *DatetimeTolerance) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type DatetimeToleranceToNow added in v1.8.0

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 added in v1.8.0

func (c *DatetimeToleranceToNow) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*DatetimeToleranceToNow) GetMessage added in v1.8.0

func (c *DatetimeToleranceToNow) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type DatetimeToleranceToOther added in v1.8.0

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 added in v1.8.0

func (c *DatetimeToleranceToOther) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*DatetimeToleranceToOther) GetMessage added in v1.8.0

func (c *DatetimeToleranceToOther) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type DatetimeYearsOld added in v1.10.9

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 added in v1.10.9

func (c *DatetimeYearsOld) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*DatetimeYearsOld) GetMessage added in v1.10.9

func (c *DatetimeYearsOld) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type DecoderProvider added in v1.8.0

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 added in v1.10.9

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 added in v1.10.9

func ParseDuration(str string) (*Duration, bool)

type EqualsOther added in v1.8.0

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 added in v1.8.0

func (c *EqualsOther) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*EqualsOther) GetMessage added in v1.8.0

func (c *EqualsOther) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type FailWhen added in v1.8.0

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 added in v1.8.0

func (c *FailWhen) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*FailWhen) GetMessage added in v1.8.0

func (c *FailWhen) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type FailWith added in v1.10.11

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 added in v1.10.11

func (c *FailWith) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*FailWith) GetMessage added in v1.10.11

func (c *FailWith) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type FailingConstraint added in v1.8.0

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 added in v1.8.0

func (c *FailingConstraint) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*FailingConstraint) GetMessage added in v1.8.0

func (c *FailingConstraint) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type GreaterThan added in v1.8.0

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 added in v1.8.0

func (c *GreaterThan) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*GreaterThan) GetMessage added in v1.8.0

func (c *GreaterThan) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type GreaterThanOrEqual added in v1.8.0

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 added in v1.8.0

func (c *GreaterThanOrEqual) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*GreaterThanOrEqual) GetMessage added in v1.8.0

func (c *GreaterThanOrEqual) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type GreaterThanOrEqualOther added in v1.8.0

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 added in v1.8.0

func (c *GreaterThanOrEqualOther) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*GreaterThanOrEqualOther) GetMessage added in v1.8.0

func (c *GreaterThanOrEqualOther) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type GreaterThanOther added in v1.8.0

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 added in v1.8.0

func (c *GreaterThanOther) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*GreaterThanOther) GetMessage added in v1.8.0

func (c *GreaterThanOther) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type I18n added in v1.8.0

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 added in v1.8.0

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 added in v1.12.1

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 added in v1.12.1

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 added in v1.12.1

func (c *IsNotNull) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type IsNull added in v1.12.1

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 added in v1.12.1

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 added in v1.12.1

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 added in v1.5.0

func JsonTypeFromString(str string) (JsonType, bool)

func (JsonType) String

func (jt JsonType) String() string

func (*JsonType) UnmarshalJSON added in v1.8.0

func (jt *JsonType) UnmarshalJSON(data []byte) error

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 added in v1.8.0

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 added in v1.8.0

func (c *LengthExact) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*LengthExact) GetMessage added in v1.8.0

func (c *LengthExact) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type LessThan added in v1.8.0

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 added in v1.8.0

func (c *LessThan) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*LessThan) GetMessage added in v1.8.0

func (c *LessThan) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type LessThanOrEqual added in v1.8.0

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 added in v1.8.0

func (c *LessThanOrEqual) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*LessThanOrEqual) GetMessage added in v1.8.0

func (c *LessThanOrEqual) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type LessThanOrEqualOther added in v1.8.0

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 added in v1.8.0

func (c *LessThanOrEqualOther) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*LessThanOrEqualOther) GetMessage added in v1.8.0

func (c *LessThanOrEqualOther) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type LessThanOther added in v1.8.0

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 added in v1.8.0

func (c *LessThanOther) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*LessThanOther) GetMessage added in v1.8.0

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 added in v1.8.0

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 added in v1.8.0

func (c *MaximumInt) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*MaximumInt) GetMessage added in v1.8.0

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 added in v1.8.0

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 added in v1.8.0

func (c *MinimumInt) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*MinimumInt) GetMessage added in v1.8.0

func (c *MinimumInt) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type MultipleOf added in v1.8.0

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 added in v1.8.0

func (c *MultipleOf) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*MultipleOf) GetMessage added in v1.8.0

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 added in v1.9.6

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 added in v1.9.6

func (c *NetIsCIDR) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*NetIsCIDR) GetMessage added in v1.9.6

func (c *NetIsCIDR) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type NetIsHostname added in v1.9.7

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 added in v1.9.7

func (c *NetIsHostname) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*NetIsHostname) GetMessage added in v1.9.7

func (c *NetIsHostname) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type NetIsIP added in v1.9.6

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 added in v1.9.6

func (c *NetIsIP) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*NetIsIP) GetMessage added in v1.9.6

func (c *NetIsIP) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type NetIsMac added in v1.9.6

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 added in v1.9.6

func (c *NetIsMac) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*NetIsMac) GetMessage added in v1.9.6

func (c *NetIsMac) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type NetIsTCP added in v1.9.6

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 added in v1.9.6

func (c *NetIsTCP) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*NetIsTCP) GetMessage added in v1.9.6

func (c *NetIsTCP) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type NetIsTld added in v1.9.6

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 added in v1.9.6

func (c *NetIsTld) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*NetIsTld) GetMessage added in v1.9.6

func (c *NetIsTld) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type NetIsUDP added in v1.9.6

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 added in v1.9.6

func (c *NetIsUDP) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*NetIsUDP) GetMessage added in v1.9.6

func (c *NetIsUDP) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type NetIsURI added in v1.9.7

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 added in v1.9.7

func (c *NetIsURI) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*NetIsURI) GetMessage added in v1.9.7

func (c *NetIsURI) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type NetIsURL added in v1.9.7

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 added in v1.9.7

func (c *NetIsURL) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*NetIsURL) GetMessage added in v1.9.7

func (c *NetIsURL) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type NotEmpty added in v1.9.9

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 added in v1.9.9

func (c *NotEmpty) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*NotEmpty) GetMessage added in v1.9.9

func (c *NotEmpty) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type NotEqualsOther added in v1.8.0

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 added in v1.8.0

func (c *NotEqualsOther) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*NotEqualsOther) GetMessage added in v1.8.0

func (c *NotEqualsOther) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type OasInfo added in v1.7.0

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

func (*OasInfo) Clone added in v1.9.0

func (oas *OasInfo) Clone() *OasInfo

type Option added in v1.11.3

type Option interface {
	Apply(on *Validator) error
}
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
)
var OptionUseNumber Option = &optionUseNumber{true}

OptionUseNumber option for ValidatorFor - sets Validator to use json.Number when decoding requests

type Other added in v1.9.0

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 added in v1.9.0

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 added in v1.9.0

func NewOtherGrouping(items ...interface{}) *OtherGrouping

func (*OtherGrouping) ANDed added in v1.9.0

func (g *OtherGrouping) ANDed() *OtherGrouping

func (*OtherGrouping) AddAndGroup added in v1.9.0

func (g *OtherGrouping) AddAndGroup(of *OthersExpr) *OtherGrouping

func (*OtherGrouping) AddAndNotGroup added in v1.9.0

func (g *OtherGrouping) AddAndNotGroup(of *OthersExpr) *OtherGrouping

func (*OtherGrouping) AddAndNotProperty added in v1.9.0

func (g *OtherGrouping) AddAndNotProperty(name string) *OtherGrouping

func (*OtherGrouping) AddAndProperty added in v1.9.0

func (g *OtherGrouping) AddAndProperty(name string) *OtherGrouping

func (*OtherGrouping) AddGroup added in v1.9.0

func (g *OtherGrouping) AddGroup(of *OthersExpr) *OtherGrouping

func (*OtherGrouping) AddNotGroup added in v1.9.0

func (g *OtherGrouping) AddNotGroup(of *OthersExpr) *OtherGrouping

func (*OtherGrouping) AddNotProperty added in v1.9.0

func (g *OtherGrouping) AddNotProperty(name string) *OtherGrouping

func (*OtherGrouping) AddOrGroup added in v1.9.0

func (g *OtherGrouping) AddOrGroup(of *OthersExpr) *OtherGrouping

func (*OtherGrouping) AddOrNotGroup added in v1.9.0

func (g *OtherGrouping) AddOrNotGroup(of *OthersExpr) *OtherGrouping

func (*OtherGrouping) AddOrNotProperty added in v1.9.0

func (g *OtherGrouping) AddOrNotProperty(name string) *OtherGrouping

func (*OtherGrouping) AddOrProperty added in v1.9.0

func (g *OtherGrouping) AddOrProperty(name string) *OtherGrouping

func (*OtherGrouping) AddProperty added in v1.9.0

func (g *OtherGrouping) AddProperty(name string) *OtherGrouping

func (*OtherGrouping) AddXorGroup added in v1.9.1

func (g *OtherGrouping) AddXorGroup(of *OthersExpr) *OtherGrouping

func (*OtherGrouping) AddXorNotGroup added in v1.9.1

func (g *OtherGrouping) AddXorNotGroup(of *OthersExpr) *OtherGrouping

func (*OtherGrouping) AddXorNotProperty added in v1.9.1

func (g *OtherGrouping) AddXorNotProperty(name string) *OtherGrouping

func (*OtherGrouping) AddXorProperty added in v1.9.1

func (g *OtherGrouping) AddXorProperty(name string) *OtherGrouping

func (*OtherGrouping) Evaluate added in v1.9.0

func (g *OtherGrouping) Evaluate(currentObj map[string]interface{}, ancestryValues []interface{}, vcx *ValidatorContext) bool

Evaluate implements Other.Evaluate

func (*OtherGrouping) GetOperator added in v1.9.0

func (g *OtherGrouping) GetOperator() BooleanOperator

GetOperator implements Other.GetOperator (always returns And)

func (*OtherGrouping) NOTed added in v1.9.0

func (g *OtherGrouping) NOTed() *OtherGrouping

func (*OtherGrouping) ORed added in v1.9.0

func (g *OtherGrouping) ORed() *OtherGrouping

func (*OtherGrouping) String added in v1.9.0

func (g *OtherGrouping) String() string

func (*OtherGrouping) XORed added in v1.9.1

func (g *OtherGrouping) XORed() *OtherGrouping

type OtherProperty added in v1.9.0

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 added in v1.9.0

func NewOtherProperty(name string) *OtherProperty

func (*OtherProperty) ANDed added in v1.9.0

func (p *OtherProperty) ANDed() *OtherProperty

func (*OtherProperty) Evaluate added in v1.9.0

func (p *OtherProperty) Evaluate(currentObj map[string]interface{}, ancestryValues []interface{}, vcx *ValidatorContext) bool

Evaluate implements Other.Evaluate

func (*OtherProperty) GetOperator added in v1.9.0

func (p *OtherProperty) GetOperator() BooleanOperator

GetOperator implements Other.GetOperator

func (*OtherProperty) NOTed added in v1.9.0

func (p *OtherProperty) NOTed() *OtherProperty

func (*OtherProperty) ORed added in v1.9.0

func (p *OtherProperty) ORed() *OtherProperty

func (*OtherProperty) String added in v1.9.0

func (p *OtherProperty) String() string

func (*OtherProperty) XORed added in v1.9.1

func (p *OtherProperty) XORed() *OtherProperty

type OthersExpr added in v1.9.0

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 added in v1.9.0

func MustParseExpression(expr string) OthersExpr

MustParseExpression is the same as ParseExpression - but panics if there is an error

func ParseExpression added in v1.9.0

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 added in v1.9.0

func (o *OthersExpr) AddAndGroup(of *OthersExpr) *OthersExpr

func (*OthersExpr) AddAndNotGroup added in v1.9.0

func (o *OthersExpr) AddAndNotGroup(of *OthersExpr) *OthersExpr

func (*OthersExpr) AddAndNotProperty added in v1.9.0

func (o *OthersExpr) AddAndNotProperty(name string) *OthersExpr

func (*OthersExpr) AddAndProperty added in v1.9.0

func (o *OthersExpr) AddAndProperty(name string) *OthersExpr

func (*OthersExpr) AddGroup added in v1.9.0

func (o *OthersExpr) AddGroup(of *OthersExpr) *OthersExpr

func (*OthersExpr) AddNotGroup added in v1.9.0

func (o *OthersExpr) AddNotGroup(of *OthersExpr) *OthersExpr

func (*OthersExpr) AddNotProperty added in v1.9.0

func (o *OthersExpr) AddNotProperty(name string) *OthersExpr

func (*OthersExpr) AddOrGroup added in v1.9.0

func (o *OthersExpr) AddOrGroup(of *OthersExpr) *OthersExpr

func (*OthersExpr) AddOrNotGroup added in v1.9.0

func (o *OthersExpr) AddOrNotGroup(of *OthersExpr) *OthersExpr

func (*OthersExpr) AddOrNotProperty added in v1.9.0

func (o *OthersExpr) AddOrNotProperty(name string) *OthersExpr

func (*OthersExpr) AddOrProperty added in v1.9.0

func (o *OthersExpr) AddOrProperty(name string) *OthersExpr

func (*OthersExpr) AddProperty added in v1.9.0

func (o *OthersExpr) AddProperty(name string) *OthersExpr

func (*OthersExpr) AddXorGroup added in v1.9.1

func (o *OthersExpr) AddXorGroup(of *OthersExpr) *OthersExpr

func (*OthersExpr) AddXorNotGroup added in v1.9.1

func (o *OthersExpr) AddXorNotGroup(of *OthersExpr) *OthersExpr

func (*OthersExpr) AddXorNotProperty added in v1.9.1

func (o *OthersExpr) AddXorNotProperty(name string) *OthersExpr

func (*OthersExpr) AddXorProperty added in v1.9.1

func (o *OthersExpr) AddXorProperty(name string) *OthersExpr

func (OthersExpr) Clone added in v1.9.0

func (src OthersExpr) Clone() OthersExpr

func (*OthersExpr) Evaluate added in v1.9.0

func (o *OthersExpr) Evaluate(currentObj map[string]interface{}, ancestryValues []interface{}, vcx *ValidatorContext) bool

Evaluate implements Other.Evaluate

func (*OthersExpr) GetOperator added in v1.9.0

func (o *OthersExpr) GetOperator() BooleanOperator

GetOperator implements Other.GetOperator (always returns And)

func (*OthersExpr) MarshalJSON added in v1.10.11

func (o *OthersExpr) MarshalJSON() ([]byte, error)

func (*OthersExpr) String added in v1.9.0

func (o *OthersExpr) String() string

func (*OthersExpr) UnmarshalJSON added in v1.9.0

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 added in v1.8.0

type PostPatternChecker interface {
	Check(str string) bool
}

type Preset added in v1.8.2

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 added in v1.8.2

func GetRegisteredPreset(token string) (Preset, bool)

type Properties

type Properties map[string]*PropertyValidator

Properties type used by Validator.Properties

func (Properties) Clone added in v1.9.0

func (src Properties) Clone() Properties

type PropertyNameProvider added in v1.9.12

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 added in v1.10.0

func CreatePropertyValidator(v8nTags ...string) *PropertyValidator

CreatePropertyValidator is the same as NewPropertyValidator - except that it panics if an error is encountered

func NewPropertyValidator added in v1.10.0

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 added in v1.9.3

func (pv *PropertyValidator) AddConstraints(c ...Constraint) *PropertyValidator

AddConstraints adds constraint(s) to the property validator

func (*PropertyValidator) AddMandatoryWhens added in v1.9.3

func (pv *PropertyValidator) AddMandatoryWhens(c ...string) *PropertyValidator

AddMandatoryWhens adds mandatory when condition token(s) to the property validator

func (*PropertyValidator) AddUnwantedConditions added in v1.9.3

func (pv *PropertyValidator) AddUnwantedConditions(c ...string) *PropertyValidator

AddUnwantedConditions adds when condition token(s) to the property validator

func (*PropertyValidator) AddWhenConditions added in v1.9.3

func (pv *PropertyValidator) AddWhenConditions(c ...string) *PropertyValidator

AddWhenConditions adds when condition token(s) to the property validator

func (*PropertyValidator) Clone added in v1.9.0

func (pv *PropertyValidator) Clone() *PropertyValidator

func (*PropertyValidator) MarshalJSON added in v1.8.0

func (pv *PropertyValidator) MarshalJSON() ([]byte, error)

func (*PropertyValidator) SetMandatory added in v1.9.3

func (pv *PropertyValidator) SetMandatory() *PropertyValidator

SetMandatory sets the property is mandatory (required) for the property validator

func (*PropertyValidator) SetNotNullable added in v1.9.3

func (pv *PropertyValidator) SetNotNullable() *PropertyValidator

SetNotNullable sets the property validator to disallow nulls

func (*PropertyValidator) SetNullable added in v1.9.3

func (pv *PropertyValidator) SetNullable() *PropertyValidator

SetNullable sets the property validator to allow nulls

func (*PropertyValidator) SetObjectValidator added in v1.9.3

func (pv *PropertyValidator) SetObjectValidator(v *Validator) *PropertyValidator

SetObjectValidator sets the object validator for the property validator

func (*PropertyValidator) SetOptional added in v1.9.3

func (pv *PropertyValidator) SetOptional() *PropertyValidator

SetOptional sets the property is optional for the property validator

func (*PropertyValidator) SetOrder added in v1.9.3

func (pv *PropertyValidator) SetOrder(order int) *PropertyValidator

SetOrder sets the property check order for the property validator

func (*PropertyValidator) SetRequired added in v1.9.3

func (pv *PropertyValidator) SetRequired() *PropertyValidator

SetRequired same as SetMandatory

func (*PropertyValidator) SetRequiredWith added in v1.9.3

func (pv *PropertyValidator) SetRequiredWith(expr OthersExpr) *PropertyValidator

SetRequiredWith sets the required with expression for the property validator

func (*PropertyValidator) SetRequiredWithMessage added in v1.9.3

func (pv *PropertyValidator) SetRequiredWithMessage(msg string) *PropertyValidator

SetRequiredWithMessage sets the required with message for the property validator

func (*PropertyValidator) SetType added in v1.9.3

SetType sets the expected type for the property validator

func (*PropertyValidator) SetUnwantedWith added in v1.9.3

func (pv *PropertyValidator) SetUnwantedWith(expr OthersExpr) *PropertyValidator

SetUnwantedWith sets the unwanted with expression for the property validator

func (*PropertyValidator) SetUnwantedWithMessage added in v1.9.3

func (pv *PropertyValidator) SetUnwantedWithMessage(msg string) *PropertyValidator

SetUnwantedWithMessage sets the unwanted with message for the property validator

func (*PropertyValidator) ToV8nTagString added in v1.11.0

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

func (*PropertyValidator) Validate added in v1.10.0

func (pv *PropertyValidator) Validate(value interface{}, initialConditions ...string) (bool, []*Violation)

Validate validates a value

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 added in v1.8.0

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 added in v1.8.0

func (c *RangeInt) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*RangeInt) GetMessage added in v1.8.0

func (c *RangeInt) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type RegionalVariantTranslation added in v1.8.0

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 added in v1.7.0

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 added in v1.7.0

func (c *SetConditionFrom) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*SetConditionFrom) GetMessage added in v1.7.0

func (c *SetConditionFrom) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type SetConditionIf added in v1.10.6

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 added in v1.10.6

func (c *SetConditionIf) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*SetConditionIf) GetMessage added in v1.10.6

func (c *SetConditionIf) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

func (*SetConditionIf) MarshalJSON added in v1.10.6

func (c *SetConditionIf) MarshalJSON() ([]byte, error)

func (*SetConditionIf) UnmarshalJSON added in v1.10.6

func (c *SetConditionIf) UnmarshalJSON(data []byte) error

type SetConditionOnType added in v1.8.1

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 added in v1.8.1

func (c *SetConditionOnType) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*SetConditionOnType) GetMessage added in v1.8.1

func (c *SetConditionOnType) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type SetConditionProperty added in v1.8.0

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 added in v1.8.0

func (c *SetConditionProperty) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*SetConditionProperty) GetMessage added in v1.8.0

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 added in v1.9.6

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 added in v1.9.6

func (c *StringContains) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*StringContains) GetMessage added in v1.9.6

func (c *StringContains) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type StringEndsWith added in v1.9.6

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 added in v1.9.6

func (c *StringEndsWith) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*StringEndsWith) GetMessage added in v1.9.6

func (c *StringEndsWith) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type StringExactLength added in v1.8.0

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 added in v1.8.0

func (c *StringExactLength) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*StringExactLength) GetMessage added in v1.8.0

func (c *StringExactLength) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type StringGreaterThan added in v1.9.6

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 added in v1.9.6

func (c *StringGreaterThan) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*StringGreaterThan) GetMessage added in v1.9.6

func (c *StringGreaterThan) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type StringGreaterThanOrEqual added in v1.9.6

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 added in v1.9.6

func (c *StringGreaterThanOrEqual) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*StringGreaterThanOrEqual) GetMessage added in v1.9.6

func (c *StringGreaterThanOrEqual) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type StringGreaterThanOrEqualOther added in v1.9.6

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 added in v1.9.6

func (c *StringGreaterThanOrEqualOther) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*StringGreaterThanOrEqualOther) GetMessage added in v1.9.6

GetMessage implements the Constraint.GetMessage

type StringGreaterThanOther added in v1.9.6

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 added in v1.9.6

func (c *StringGreaterThanOther) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*StringGreaterThanOther) GetMessage added in v1.9.6

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 added in v1.9.6

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 added in v1.9.6

func (c *StringLessThan) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*StringLessThan) GetMessage added in v1.9.6

func (c *StringLessThan) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type StringLessThanOrEqual added in v1.9.6

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 added in v1.9.6

func (c *StringLessThanOrEqual) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*StringLessThanOrEqual) GetMessage added in v1.9.6

func (c *StringLessThanOrEqual) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type StringLessThanOrEqualOther added in v1.9.6

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 added in v1.9.6

func (c *StringLessThanOrEqualOther) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*StringLessThanOrEqualOther) GetMessage added in v1.9.6

func (c *StringLessThanOrEqualOther) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type StringLessThanOther added in v1.9.6

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 added in v1.9.6

func (c *StringLessThanOther) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*StringLessThanOther) GetMessage added in v1.9.6

func (c *StringLessThanOther) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type StringLowercase added in v1.8.0

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 added in v1.8.0

func (c *StringLowercase) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*StringLowercase) GetMessage added in v1.8.0

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 added in v1.8.0

func (c *StringPattern) MarshalJSON() ([]byte, error)

func (*StringPattern) UnmarshalJSON added in v1.8.0

func (c *StringPattern) UnmarshalJSON(data []byte) error

type StringPresetPattern added in v1.8.0

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 added in v1.8.0

func (c *StringPresetPattern) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*StringPresetPattern) GetMessage added in v1.8.0

func (c *StringPresetPattern) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type StringStartsWith added in v1.9.6

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 added in v1.9.6

func (c *StringStartsWith) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*StringStartsWith) GetMessage added in v1.9.6

func (c *StringStartsWith) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type StringUppercase added in v1.8.0

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 added in v1.8.0

func (c *StringUppercase) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*StringUppercase) GetMessage added in v1.8.0

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 added in v1.9.6

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 added in v1.9.6

func (c *StringValidCountryCode) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*StringValidCountryCode) GetMessage added in v1.9.6

func (c *StringValidCountryCode) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type StringValidCurrencyCode added in v1.9.6

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 added in v1.9.6

func (c *StringValidCurrencyCode) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*StringValidCurrencyCode) GetMessage added in v1.9.6

func (c *StringValidCurrencyCode) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type StringValidEmail added in v1.6.0

type StringValidEmail struct {
	// DisallowRFC5322 when set, disallows email addresses in RFC5322 format (i.e "Barry Gibbs <bg@example.com>")
	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. "me@some-company.africa")
	AllowGeographicTlds bool
	// AllowGenericTlds when set, allows email addresses with generic Tlds (e.g. "me@some.academy")
	AllowGenericTlds bool
	// AllowBrandTlds when set, allows email addresses with brand Tlds (e.g. "me@my.audi")
	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. "me@example.com", "me@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 `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 added in v1.6.0

func (c *StringValidEmail) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*StringValidEmail) GetMessage added in v1.6.0

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 added in v1.10.9

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 added in v1.10.9

func (c *StringValidISODuration) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*StringValidISODuration) GetMessage added in v1.10.9

func (c *StringValidISODuration) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type StringValidJson added in v1.9.6

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 added in v1.9.6

func (c *StringValidJson) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*StringValidJson) GetMessage added in v1.9.6

func (c *StringValidJson) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type StringValidLanguageCode added in v1.9.6

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 added in v1.9.6

func (c *StringValidLanguageCode) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*StringValidLanguageCode) GetMessage added in v1.9.6

func (c *StringValidLanguageCode) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type StringValidTimezone added in v1.9.6

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 added in v1.9.6

func (c *StringValidTimezone) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*StringValidTimezone) GetMessage added in v1.9.6

func (c *StringValidTimezone) GetMessage(tcx I18nContext) string

GetMessage implements the Constraint.GetMessage

type StringValidToken added in v1.0.3

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 added in v1.0.3

func (c *StringValidToken) Check(v interface{}, vcx *ValidatorContext) (bool, string)

Check implements Constraint.Check

func (*StringValidToken) GetMessage added in v1.0.3

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

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 added in v1.9.0

type TagAliases map[string]string

type TagHandler added in v1.9.0

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 added in v1.9.2

type Time struct {
	time.Time
	Original string
}

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) IsSet added in v1.9.2

func (t *Time) IsSet() bool

func (*Time) MarshalJSON added in v1.9.2

func (t *Time) MarshalJSON() ([]byte, error)

func (*Time) UnmarshalJSON added in v1.9.2

func (t *Time) UnmarshalJSON(b []byte) error

type Translator added in v1.8.0

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 added in v1.11.0

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 added in v1.7.0

type ValidationError struct {
	Message      string
	Violations   []*Violation
	IsBadRequest bool
}

func (*ValidationError) Error added in v1.7.0

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 added in v1.5.0

func MustCompileValidatorFor(vstruct interface{}, options ...Option) *Validator

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 added in v1.5.0

func ValidatorFor(vstruct interface{}, options ...Option) (*Validator, error)

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) Clone added in v1.9.0

func (v *Validator) Clone() *Validator

func (*Validator) IsOrderedPropertyChecks added in v1.7.0

func (v *Validator) IsOrderedPropertyChecks() bool

func (*Validator) MarshalJSON added in v1.8.0

func (v *Validator) MarshalJSON() ([]byte, error)

func (*Validator) RequestQueryValidate added in v1.9.11

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 added in v1.9.11

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 added in v1.5.0

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 added in v1.7.0

func (v *Validator) ValidateInto(data []byte, value interface{}, initialConditions ...string) error

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 added in v1.5.0

func (v *Validator) ValidateReader(r io.Reader, initialConditions ...string) (bool, []*Violation, interface{})

ValidateReader performs validation on the supplied reader (representing JSON)

func (*Validator) ValidateReaderInto added in v1.5.0

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 added in v1.5.0

func (v *Validator) ValidateString(s string, initialConditions ...string) (bool, []*Violation, interface{})

ValidateString performs validation on the supplied string (representing JSON)

func (*Validator) ValidateStringInto added in v1.5.0

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 added in v1.9.9

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 added in v1.8.0

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 added in v1.7.0

func (vc *ValidatorContext) ClearCondition(condition string)

ClearCondition clears a specified condition (token)

func (*ValidatorContext) ClearGlobalCondition added in v1.8.0

func (vc *ValidatorContext) ClearGlobalCondition(condition string)

ClearGlobalCondition clears a specified condition (token) on the parent in the object tree

func (*ValidatorContext) ClearParentCondition added in v1.8.0

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 added in v1.7.0

func (vc *ValidatorContext) IsCondition(condition string) bool

IsCondition checks whether a specified condition (token) has been set

func (*ValidatorContext) Language added in v1.8.0

func (vc *ValidatorContext) Language() string

Language implements I18nContext.Language (and relays it to internal i18nContext)

func (*ValidatorContext) Lock added in v1.10.6

func (vc *ValidatorContext) Lock()

func (*ValidatorContext) Region added in v1.8.0

func (vc *ValidatorContext) Region() string

Region implements I18nContext.Region (and relays it to internal i18nContext)

func (*ValidatorContext) SetCondition added in v1.7.0

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 added in v1.8.0

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 added in v1.8.0

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 added in v1.8.0

func (vc *ValidatorContext) TranslateFormat(format string, a ...interface{}) string

TranslateFormat implements I18nContext.TranslateFormat (and relays it to internal i18nContext)

func (*ValidatorContext) TranslateMessage added in v1.8.0

func (vc *ValidatorContext) TranslateMessage(msg string) string

TranslateMessage implements I18nContext.TranslateMessage (and relays it to internal i18nContext)

func (*ValidatorContext) TranslateToken added in v1.8.0

func (vc *ValidatorContext) TranslateToken(token string) string

TranslateToken implements I18nContext.TranslateToken (and relays it to internal i18nContext)

func (*ValidatorContext) UnLock added in v1.10.6

func (vc *ValidatorContext) UnLock()

func (*ValidatorContext) ValuesAncestry added in v1.9.0

func (vc *ValidatorContext) ValuesAncestry() []interface{}

ValuesAncestry returns the values ancestry (where the first item is parent, second is grandparent etc.)

type ValidatorForOptions added in v1.5.0

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 added in v1.11.3

func (o *ValidatorForOptions) Apply(on *Validator) error

type VariablePropertyConstraint added in v1.8.0

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 added in v1.8.0

func (c *VariablePropertyConstraint) Check(v interface{}, vcx *ValidatorContext) (bool, string)

func (*VariablePropertyConstraint) GetMessage added in v1.8.0

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

func NewBadRequestViolation(msg string, codes ...interface{}) *Violation

NewBadRequestViolation creates a new violation with BadRequest flag set (path and property are blank)

func NewEmptyViolation

func NewEmptyViolation(msg string, codes ...interface{}) *Violation

NewEmptyViolation creates a new violation with the specified message (path and property are blank)

func NewViolation

func NewViolation(property string, path string, msg string, codes ...interface{}) *Violation

NewViolation creates a new violation with the specified property, path and message

Jump to

Keyboard shortcuts

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