Skip to content

constraint.ArrayOf

marrow16 edited this page Jan 21, 2023 · 5 revisions

Prev Home Next

Constraint: ArrayOf

Description

Check each element in an array value is of the correct type

V8n Tag Abbreviation

aof

Fields

Field Type Description
Type string the type to check for each item
AllowNullElement bool whether to allow null items in the array
Constraints Constraints is an optional list of constraints that each array element must satisfy
Message string the violation message to be used if the constraint fails
Stop bool when set to true, Stop prevents further validation checks on the property if this constraint fails

Examples

Programmatic example...
package main

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

func main() {
    validator := &valix.Validator{
        Properties: valix.Properties{
            "foo": {
                Type: valix.JsonArray,
                Constraints: valix.Constraints{
                    &valix.ArrayOf{
                        Type: "integer",
                    },
                },
            },
        },
    }
    obj := `{
        "foo": [1.1, 1, 2]
    }`

    ok, violations, _ := validator.ValidateString(obj)
    fmt.Printf("Passed? %v\n", ok)
    for i, v := range violations {
        fmt.Printf("Violation[%d] Message: %s, Property: %s, Path: %s", i+1, v.Message, v.Property, v.Path)
    }
}

try on go-playground

Struct v8n tag example...
package main

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

type MyStruct struct {
    Foo []string `json:"foo" v8n:"&aof{Type:'integer'}"`
}

var validator = valix.MustCompileValidatorFor(MyStruct{}, nil)

func main() {
    obj := `{"foo": [1.1, 1, 2]}`

    ok, violations, _ := validator.ValidateString(obj)
    fmt.Printf("Passed? %v\n", ok)
    for i, v := range violations {
        fmt.Printf("Violation[%d] Message: %s, Property: %s, Path: %s", i+1, v.Message, v.Property, v.Path)
    }
}

try on go-playground

Clone this wiki locally