Skip to content

constraint.StringValidISODuration

marrow16 edited this page Jan 21, 2023 · 5 revisions

Prev Home Next

Constraint: StringValidISODuration

Description

Check that a string value is a valid ISO8601 Duration

V8n Tag Abbreviation

strisodur

Fields

Field Type Description
DisallowNegative bool if set, disallows negative durations (e.g. "-P1Y")
Message string the violation message to be used if the constraint fails. If empty, the default message is used
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{
        UseNumber: true,
        Properties: valix.Properties{
            "foo": {
                Type: valix.JsonString,
                Constraints: valix.Constraints{
                    &valix.StringValidISODuration{},
                },
            },
        },
    }

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

    ok, violations, _ = validator.ValidateString(`{"foo": "P1Y2M3DT4H5M6S"}`)
    fmt.Printf("Passed? %v\n", ok)
    for i, v := range violations {
        fmt.Printf("Violation[%d] Message: %s, Property: %s, Path: %s\n", 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:"&strisodur"`
}

var validator = valix.MustCompileValidatorFor(MyStruct{})

func main() {
    my := &MyStruct{}

    ok, violations, _ := validator.ValidateStringInto(`{"foo": "not a valid duration"}`, my)
    fmt.Printf("Passed? %v\n", ok)
    for i, v := range violations {
        fmt.Printf("Violation[%d] Message: %s, Property: %s, Path: %s\n", i+1, v.Message, v.Property, v.Path)
    }

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

try on go-playground

Clone this wiki locally