Help us shape the future of Go! Take the 2026 Go Developer Survey

yamlvalidator

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2026 License: Apache-2.0 Imports: 3 Imported by: 0

README

yamlvalidator

CI Measured statement coverage Go Reference Release License Go version Mentioned in Awesome Go

Source-aware YAML validation and typed YAML codecs for Go. Validate Go struct tags, native Go schemas, or full JSON Schema while preserving paths, lines, and columns in diagnostics.

[ERROR] line 3:1: unknown key "plugin"; did you mean "plugins"? (path: generate.plugin)
>    3 | plugin:
       | ^

For typed application configuration, put rules next to Go fields with yamlvalidate and use yamlvalidator.Unmarshal / yamlvalidator.Marshal. Use FieldSchema when you need a programmatic native contract, or bring an existing JSON Schema when portability matters. Validation runs against the YAML representation before application decoding.

Why this library?

The comparison below covers the libraries' documented APIs, not every integration that could be built on top of them. The JSON Schema column refers to the Go library, not its separate CLI.

Need yaml.v3 goccy/go-yaml go-playground/validator santhosh-tekuri/jsonschema go-yamlvalidator
YAML parsing and Marshal/Unmarshal Yes Yes No; validates Go values No YAML codec in library API Yes; uses yaml.v3
Validation diagnostics with YAML source locations Manual via yaml.Node Validator integration and YAML Path annotations No YAML source mapping JSON instance paths; needs YAML source mapping Paths, lines, columns and source snippets
Go struct-tag validation Not built in Via StructValidator on decoded values Yes, on Go values No Native tags checked on YAML before decoding
JSON Schema validation Not built in Not built in No Yes Yes, with YAML source diagnostics
Custom Go validation Manual hooks StructValidator integration Field and struct callbacks Formats and vocabularies Value/key validators and registry
Unknown struct/object keys KnownFields(true) DisallowUnknownField() Not recoverable once discarded by struct decoding additionalProperties Error/warn/ignore policies and key suggestions

goccy/go-yaml already provides source-aware errors: its validator integration can annotate field-validation failures, YAML Path can annotate custom errors, and unknown-field rejection includes source context. It should not be treated as a decoder without validation support. The distinction here is validation of the original YAML tree before decoding into an application struct, with native schemas, struct tags, JSON Schema and optional typed code generation in one library.

Originally built to validate configuration files in EasyP. The development story is in this Habr article (Russian).

Installation

Requires Go 1.24 or newer. CI verifies the minimum supported Go 1.24 line and the current stable Go release. Security-fixed IDNA/Unicode code is kept in an internal third-party snapshot so full idn-hostname/idn-email support does not force consumers onto Go 1.25.

go get github.com/Yakwilik/go-yamlvalidator@v1.1.0

Quick Start

Validated Go values with struct tags

For typed configuration, the shortest path is a normal Go struct with yaml and yamlvalidate tags:

type Config struct {
    Mode  string   `yaml:"mode" yamlvalidate:"required,enum=[dev,prod]"`
    File  string   `yaml:"file,omitempty" yamlvalidate:"exactlyOneOf=[file,url],nonempty"`
    URL   string   `yaml:"url,omitempty"`
    Hosts []string `yaml:"hosts" yamlvalidate:"required,minItems=1,items={nonempty,format=hostname}"`
}

var config Config
if err := yamlvalidator.Unmarshal(data, &config); err != nil {
    return err
}

encoded, err := yamlvalidator.Marshal(config)

Unmarshal parses one YAML document, validates the source tree, and only then decodes into the destination. A validation failure does not mutate the destination. Unknown struct fields are errors by default. Marshal validates the YAML representation it actually emits, so omitempty, inline fields, and custom codecs affect validation exactly as they affect output.

In v1.2.0, use FieldNamingGo when existing YAML keys match exported Go field names, including case:

options := yamlvalidator.UnmarshalOptions{
    FieldNaming:      yamlvalidator.FieldNamingGo,
    WarningsAsErrors: true,
}
err := options.Unmarshal(data, &config)
encoded, err := (yamlvalidator.MarshalOptions{
    FieldNaming: yamlvalidator.FieldNamingGo,
    Indent:      2,
}).Marshal(config)

Explicit yaml names take priority; json tags do not affect YAML names. The mode applies recursively, including inline structs, while map keys remain literal data. It still applies with SkipValidation: true. Zero-value options and package Marshal/Unmarshal keep standard lowercase YAML names. See the complete field-naming example.

Object rules have explicit scopes. A bare group such as exactlyOneOf=[file,url] on a real struct field constrains sibling keys in the containing mapping, even when the carrier field is absent. The Keys form, such as exactlyOneOfKeys=[file,url], constrains the mapping value of the current field.

See the high-level API guide for the complete tag language, registry bindings, diagnostics, limits, nested items/values, and recursive types. The runnable example defines a complete configuration.

Optional typed code generation

Generate methods for existing Go types without changing their definitions:

go run github.com/Yakwilik/go-yamlvalidator/cmd/yamlvalidator-gen -all -output=zz_yamlvalidator_generated.go

Generated types support ordinary yaml.v3 Marshal/Unmarshal through standard YAML hooks, as well as yamlvalidator Options. Use -all to generate every eligible named struct in the package without maintaining a type list; nested statically known types are followed transitively.

The generated file contains typed field/collection mapping and a normalized native schema graph. It does not inspect generated structs with reflection or parse yamlvalidate tags at runtime. Generated hook mechanics live in the dedicated genruntime package; the application-facing root package exposes no generator bridge functions. Reflection remains only in fallback paths for non-generated or genuinely dynamic values.

See code generation, generated runtime architecture, the benchmark suite, the runnable generated example, and cross-field rule examples in Russian.

Native schema validation
package main

import (
    "fmt"

    v "github.com/Yakwilik/go-yamlvalidator"
)

func main() {
    schema := &v.FieldSchema{
        Type:             v.TypeMap,
        UnknownKeyPolicy: v.UnknownKeyError,
        AllowedKeys: map[string]*v.FieldSchema{
            "name": {Type: v.TypeString, Required: true},
            "port": {Type: v.TypeInt},
        },
    }

    data := []byte("name: api\nport: 8080\n")
    result := v.NewValidator(schema).ValidateBytes(data)

    if result.HasErrors() {
        fmt.Print(result.FormatAll(true))
    }
}

Schema Definition

Field Schema
type FieldSchema struct {
    // Basic properties
    Type         NodeType   // Expected type (TypeString, TypeInt, etc.)
    AllowedTypes []NodeType // Accept any listed type; takes precedence over Type
    Required     bool       // Field must be present
    Nullable    bool        // Allow null values
    Deprecated  string      // Deprecation message (empty = not deprecated)
    Description string      // Human-readable description
    Default     interface{} // Suggested default; emits warning if omitted, does not mutate input

    // Map-specific
    AllowedKeys          map[string]*FieldSchema // Known keys
    AdditionalProperties *FieldSchema            // Schema for unknown keys
    UnknownKeyPolicy     UnknownKeyPolicy        // How to handle unknown keys
    KeyValidators        []KeyValidator          // Key name validators

    // Sequence-specific
    ItemSchema *FieldSchema // Schema for items
    MinItems   *int
    MaxItems   *int

    // Value validators
    Validators []ValueValidator

    // Inter-field logic
    AnyOf             [][]string        // At least one group must be present
    ExactlyOneOf      []string          // Exactly one field must be present
    MutuallyExclusive []string          // At most one field can be present
    Conditions        []ConditionalRule // Conditional validation
    OneOfRequired     [][]string        // Exactly one field group must be present
    ForbiddenTogether [][]string        // A complete field group is forbidden
    DependentRequired map[string][]string

    // Schema composition
    OneOfSchemas []*FieldSchema // Exactly one schema must match
    AnyOfSchemas []*FieldSchema // At least one schema must match
}
Native schema compilation

For schemas assembled dynamically, prefer CompileFieldSchema over constructing a validator directly. It rejects invalid schema graphs before any YAML is validated: recursive graphs, incompatible map/sequence constraints, invalid min/max bounds, nil validators, bad regexp definitions, invalid inter-field references, and other definition errors.

validator, err := v.CompileFieldSchema(schema)
if err != nil {
    return err
}

CompileFieldSchema also snapshots the FieldSchema graph (maps, slices, nested schemas, item limits, conditions, and ordinary JSON/YAML container defaults). Later mutations of the source schema therefore do not change the compiled validator. Opaque application-defined objects stored in Default, plus custom ValueValidator / KeyValidator instances, are copied by value and remain the caller's concurrency responsibility. A compiled validator can otherwise be reused concurrently.

NewValidator remains available for backwards compatibility when the schema is already trusted; unlike CompileFieldSchema, it retains the supplied schema pointer directly.

Node Types
Type Description
TypeAny Any type; bare maps/sequences are not recursively constrained
TypeNull Null values only
TypeString String values
TypeInt Integer values
TypeFloat Float values (also accepts int)
TypeBool Boolean values
TypeMap Mapping nodes
TypeSequence Sequence/array nodes
Unknown Key Policy
Policy Behavior
UnknownKeyInherit Uses ctx.StrictKeys (default)
UnknownKeyError Unknown keys are errors
UnknownKeyWarn Unknown keys are warnings
UnknownKeyIgnore Unknown keys are ignored

JSON Schema Compilation

CompileJSONSchema compiles a standards-compliant JSON Schema and returns a FieldSchema adapter. Validation is delegated to a full JSON Schema engine; the YAML validator remains responsible for parsing YAML, preserving source positions, resolving YAML aliases/merge keys, converting the YAML value to the JSON data model, and mapping JSON Schema errors back to YAML diagnostics.

Supported dialects:

  • JSON Schema draft-04
  • JSON Schema draft-06
  • JSON Schema draft-07
  • JSON Schema 2019-09
  • JSON Schema 2020-12

An explicit $schema selects the dialect. Without $schema, draft 2020-12 is used by default and can be changed with DefaultDraft.

All keywords implemented by the engine are available, including references and modern applicators such as $ref, $dynamicRef, $defs, $anchor, allOf, anyOf, oneOf, if/then/else, dependentSchemas, unevaluatedProperties, unevaluatedItems, prefixItems, contains, numeric/string/object/array constraints, boolean schemas, annotations, and vocabulary declarations. Unknown extension keywords follow JSON Schema semantics instead of being rejected merely because yamlvalidator does not know them.

schemaJSON, err := os.ReadFile("config.schema.json")
if err != nil {
    return err
}

schema, err := v.CompileJSONSchema(schemaJSON)
if err != nil {
    return err
}

result := v.NewValidator(schema).ValidateBytes(yamlData)
Compilation options
policy := v.UnknownKeyWarn
schema, err := v.CompileJSONSchemaWithOptions(schemaJSON, v.JSONSchemaCompileOptions{
    SchemaURL:    "https://schemas.example.com/config.json",
    DefaultDraft: v.JSONSchemaDraft2020,

    AssertFormat:  true,
    AssertContent: true,
    AssertVocabs:  true,
    RegexpTimeout: 500 * time.Millisecond, // Optional protection for untrusted schemas

    Resources: map[string][]byte{
        "https://schemas.example.com/common.json": commonSchema,
    },

    Resolver: v.NewJSONSchemaCachingResolver(
        v.JSONSchemaResolverFunc(func(ctx context.Context, url string) ([]byte, error) {
            return loadSchemaResource(ctx, url)
        }),
    ),

    AdditionalPropertiesFalsePolicy: &policy,
})

Resources preloads a closed schema graph without I/O. Compilation is closed-world by default: unresolved external references do not read the filesystem or network. Set Resolver explicitly to resolve them. Built-in resolver helpers include JSONSchemaResourceMap, JSONSchemaResolverChain, JSONSchemaCachingResolver, and the root-constrained JSONSchemaFileResolver.

For cancellable resolution/compilation use CompileJSONSchemaContext or CompileJSONSchemaContextWithOptions. Cancellation is checked around library-controlled work and is propagated into resolvers; the underlying JSON Schema engine does not expose an interrupt hook in the middle of one synchronous compile/validate call. HTTP(S) fetching is deliberately not enabled implicitly.

RegexpTimeout limits one ECMAScript regexp match. The default value 0 preserves unlimited matching for full compatibility; set a positive duration when validating against untrusted schemas.

Custom formats, content encodings, content media types, and vocabularies are registered through yamlvalidator-owned types, so callers do not need to import the underlying JSON Schema engine:

schema, err := v.CompileJSONSchemaWithOptions(schemaJSON, v.JSONSchemaCompileOptions{
    AssertContent: true,
    ContentEncodings: []v.JSONSchemaContentEncoding{
        {
            Name:   "my-encoding",
            Decode: decodeMyEncoding,
        },
    },
    ContentMediaTypes: []v.JSONSchemaContentMediaType{
        {
            Name:     "application/x-example",
            Validate: validateExampleMediaType,
        },
    },
})
Functional JSON Schema extensions

For common extension cases, yamlvalidator exposes its own API so callers do not need to depend directly on the underlying JSON Schema engine.

A custom format is useful for scalar validation and can also validate mapping keys through propertyNames:

schema, err := v.CompileJSONSchemaWithOptions(schemaJSON, v.JSONSchemaCompileOptions{
    AssertFormat: true,
    Formats: []v.JSONSchemaFormat{
        {
            Name: "module-name",
            Validate: func(value any) error {
                name, ok := value.(string)
                if ok && !validModuleName(name) {
                    return fmt.Errorf("invalid module name")
                }
                return nil
            },
        },
    },
})

The schema can then use {"format":"module-name"} or {"propertyNames":{"format":"module-name"}}.

For arbitrary business logic, register a functional custom keyword. The simplest form is literally a validation function receiving the keyword value from the schema and the current instance value:

keyword := v.JSONSchemaKeyword{
    Name: "x-require-property",
    Validate: func(raw, instance any, ctx *v.JSONSchemaKeywordValidationContext) {
        property, ok := raw.(string)
        if !ok {
            ctx.AddError("x-require-property expects a string")
            return
        }
        object, ok := instance.(map[string]any)
        if !ok {
            return
        }

        ctx.MarkPropertyEvaluated(property)
        if _, ok := object[property]; !ok {
            ctx.AddErrorAt([]string{property}, "required by x-require-property")
        }
    },
}

schema, err := v.CompileJSONSchemaWithOptions(schemaJSON, v.JSONSchemaCompileOptions{
    Keywords: []v.JSONSchemaKeyword{keyword},
})

If keyword configuration needs parsing or validation, use Compile instead of Validate; it receives the keyword value once at schema compilation time and returns a JSONSchemaKeywordValidateFunc for subsequent instance validation.

Keywords that contain nested schemas can use CompileWithContext instead of importing the underlying engine. Declare where nested schemas may occur, compile exact branches with Subschema or Reference, then validate them through ValidateSubschema:

keyword := v.JSONSchemaKeyword{
    Name: "x-dispatch",
    Subschemas: []v.JSONSchemaSubschemaPath{
        {v.JSONSchemaSubschemaAllProperties()},
    },
    CompileWithContext: func(
        ctx *v.JSONSchemaKeywordCompileContext,
        raw any,
    ) (v.JSONSchemaKeywordValidateFunc, error) {
        config := raw.(map[string]any)
        branches := make(map[string]*v.JSONSchemaSubschema, len(config))
        for name := range config {
            branches[name] = ctx.Subschema(name)
        }

        return func(instance any, validation *v.JSONSchemaKeywordValidationContext) {
            object, _ := instance.(map[string]any)
            kind, _ := object["kind"].(string)
            if branch := branches[kind]; branch != nil {
                validation.ValidateSubschema(branch, instance, nil)
            } else {
                validation.AddErrorAt([]string{"kind"}, "unknown kind")
            }
        }, nil
    },
}

Subschema location helpers cover an exact property, all property values, an exact array item, or all array items. Nested schemas keep normal JSON Schema reference semantics, including $ref.

JSONSchemaKeywordValidationContext supports multiple diagnostics through AddError / AddErrorAt and integrates with unevaluatedProperties / unevaluatedItems through MarkPropertyEvaluated / MarkItemEvaluated. Relative issue paths are mapped back to the corresponding YAML line and column, and the keyword name becomes the diagnostic Code.

For a named set of keywords use JSONSchemaVocabulary{URL, Keywords} through JSONSchemaCompileOptions.Vocabularies. First-class functional vocabularies are activated for that compilation automatically. Set JSONSchemaVocabulary.Schema when the vocabulary should validate the shape of its own keyword declarations before compiling the instance schema.

Custom keyword validators operate on the JSON data model (map[string]any, []any, json.Number, strings, booleans, null), not on yaml.Node. Treat the supplied instance as read-only; compiled schemas may be reused concurrently, so captured validator state must be concurrency-safe. YAML-specific validation that needs tags/styles/comments should continue to use native ValueValidator / KeyValidator.

Format and content assertions

For 2019-09 and 2020-12, format remains annotation-only unless the schema vocabulary requires assertions or AssertFormat is enabled. The validator supplies stricter implementations for email, hostname, IPv4, duration, URI, URI-reference, URI-template, idn-email, and idn-hostname, and uses an ECMAScript-compatible regexp engine for JSON Schema patterns and regex format validation.

AssertContent enables contentEncoding, contentMediaType, and contentSchema assertions supported by the engine.

YAML to JSON data model

JSON Schema validates the JSON data model. During validation yamlvalidator converts the YAML AST without losing source locations:

  • YAML mappings become JSON objects; mapping keys therefore must be strings.
  • YAML sequences become JSON arrays.
  • YAML integers and finite floating-point values are converted using exact textual numbers rather than float64 round-tripping.
  • YAML hexadecimal, binary, octal, and legacy octal integers are normalized to their mathematical JSON integer value.
  • YAML aliases and merge keys are resolved before JSON Schema validation.
  • YAML .nan and .inf are rejected because JSON has no non-finite numeric values.
  • YAML custom-tagged scalar values are represented as their scalar string value.

Diagnostics preserve the YAML path, line, column, JSON Schema keyword in Code, and originating schema location in SchemaPath.

Conformance

The JSON Schema adapter is exercised in CI against the official JSON-Schema-Test-Suite using the public CompileJSONSchema and YAML validation path:

  • draft-04: 618/618 core tests
  • draft-06: 841/841 core tests
  • draft-07: 929/929 core tests
  • 2019-09: 1261/1261 core tests
  • 2020-12: 1301/1301 core tests
  • total: 4950/4950 core tests

The same public API also passes 3884/3885 official optional tests when JSON string values are represented losslessly through YAML escapes where necessary. The single remaining optional draft-04 case is zeroTerminatedFloats, which intentionally tests host-language numeric type distinctions by expecting JSON 1.0 not to satisfy integer. yamlvalidator follows the engine's mathematical JSON Schema numeric semantics, where an exactly integral numeric value satisfies integer.

Optional coverage includes ECMAScript pattern semantics, email, idn-email, hostname, idn-hostname, duration, URI, URI-reference, URI-template, content assertions, and format-regex validation. Raw YAML still obeys YAML's own character restrictions; code points such as U+0085 or U+FFFF can be supplied through YAML escapes when a JSON Schema format test needs those exact scalar values.

AdditionalPropertiesFalsePolicy is a yamlvalidator presentation option: it can downgrade or suppress a direct additionalProperties: false diagnostic for editor-style workflows. It does not rewrite JSON Schema combinator semantics.

Built-in Validators

Value Validators
// Enum validation
EnumValidator{Allowed: []string{"v1", "v2", "v3"}}

// Regex validation
RegexValidator{
    Pattern: regexp.MustCompile(`^[a-z]+$`),
    Message: "must be lowercase letters",
}

// Numeric range. YAML input is compared exactly (no float64 round-trip).
RangeValidator{Min: v.Ptr[float64](1), Max: v.Ptr[float64](100)}

// Exact bounds for values that cannot be represented safely as float64.
RangeValidator{
    MinExact: MustExactNumber("9007199254740993"),
}

// Non-empty check
NonEmptyValidator{}

// Length validation
LengthValidator{Min: v.Ptr[int](1), Max: v.Ptr[int](255)}

// URL validation
URLValidator{RequireScheme: true, AllowedSchemes: []string{"http", "https"}}
Key Validators
// Regex key validation
RegexKeyValidator{
    Pattern: regexp.MustCompile(`^[a-z][a-z0-9._-]*$`),
    Message: "invalid key format",
}

// Forbidden keys
ForbiddenKeyValidator{Forbidden: []string{"password", "secret"}}

// Key length
LengthKeyValidator{Min: v.Ptr[int](1), Max: v.Ptr[int](63)}

Inter-field Logic

AnyOf (at least one group)
// Either configFile, OR both host AND port
AnyOf: [][]string{{"configFile"}, {"host", "port"}}
ExactlyOneOf (exactly one field)
// Exactly one of inline/file/url
ExactlyOneOf: []string{"inline", "file", "url"}
MutuallyExclusive (at most one)
// debug and quiet cannot both be present
MutuallyExclusive: []string{"debug", "quiet"}
Conditional Rules
Conditions: []ConditionalRule{
    {
        ConditionField: "type",
        ConditionValue: "external",
        ThenRequired:   []string{"endpoint"},
        ThenForbidden:  []string{"local"},
    },
}

Validation Options

result := validator.ValidateWithOptions(yaml, ValidationContext{
    StrictKeys:     true,  // Unknown keys are errors for native FieldSchema
    StopOnFirst:    false, // Continue after first error
    StrictTypes:    false, // Parse values for native FieldSchema type inference
    YAML11Booleans: false, // Plain YAML 1.1 yes/no/on/off compatibility

    MaxBytes:       2 << 20, // 2 MiB; 0 = unlimited
    MaxDocuments:   10,      // 0 = unlimited
    MaxDepth:       100,     // root value has depth 1; 0 = unlimited
    MaxDiagnostics: 100,     // 0 = unlimited
})
if result.Truncated {
    // MaxDiagnostics was reached.
}

For cancellation/deadlines use the context-aware API:

runCtx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()

result, err := validator.ValidateContextWithOptions(runCtx, yaml, ValidationContext{
    MaxDepth: 100,
})
if errors.Is(err, context.DeadlineExceeded) {
    // result may contain diagnostics collected before cancellation.
}

Cancellation is cooperative. Native traversal and custom validators can observe it through ValidationContext.Context(). A custom validator performing blocking work should select on or pass that context to the operation. Cancellation is checked around YAML traversal/conversion and JSON Schema validation, but it cannot interrupt an already-running yaml.Decoder.Decode call or an in-progress validation call inside the underlying JSON Schema engine.

CLI

The CLI supports both the native serialized FieldSchema format and standards-compliant JSON Schema. Native schemas are compiled and checked for definition errors before validation.

Native FieldSchema:

go run ./cmd/yamlvalidator \
  -schema /tmp/schema.yaml \
  -schema-format field \
  -file ./path/to/config.yaml \
  -strict-keys

Standard JSON Schema, including relative file $ref resolution from the schema file location:

go run ./cmd/yamlvalidator \
  -schema ./schemas/config.schema.json \
  -schema-format jsonschema \
  -file ./config.yaml \
  -assert-format \
  -regexp-timeout 500ms

JSON Schema CLI options: -json-schema-draft, -assert-format, -assert-content, -assert-vocabs, and -regexp-timeout. Validation safety limits are exposed as -max-bytes, -max-documents, -max-depth, and -max-diagnostics. Existing options include -stop-on-first, -yaml11-bools, -sort, plus native-schema-only -strict-keys and -strict-types.

Error Handling

Error Levels
  • LevelError - Critical validation failures
  • LevelWarning - Non-critical issues (deprecated fields, unknown keys in permissive mode)
Error Formatting
result := validator.ValidateBytes(yaml)

// Get all errors
for _, err := range result.Collector.Errors() {
    fmt.Println(err)
}

// Format with source context
fmt.Println(result.FormatAll(true)) // true = sort by position
Example Output
[ERROR] line 2:13: invalid value "v3" (expected one of [v1 v1beta1 apps/v1], got v3) (path: apiVersion)
     1 |
>    2 | apiVersion: v3
       |             ^
     3 | kind: Deployment

[ERROR] line 5:9: must be lowercase DNS-compatible name (got MyApp) (path: metadata.name)
     4 | metadata:
>    5 |   name: MyApp
       |         ^
     6 |   namespace: production

Multi-Document Support

The validator automatically handles multi-document YAML (separated by ---):

name: first
---
name: second
---
name: third

Errors in subsequent documents are prefixed with doc[N].:

[ERROR] line 5:1: required field "name" is missing (path: doc[2].name)

Custom Validators

Value Validator
type MyValidator struct{}

func (v MyValidator) Validate(node *yaml.Node, path string, ctx *ValidationContext) {
    if node.Value != "expected" {
        ctx.AddError(ValidationError{
            Level:   LevelError,
            Path:    path,
            Line:    node.Line,
            Column:  node.Column,
            Message: "value is not expected",
            Got:     node.Value,
        })
    }
}
Key Validator
type MyKeyValidator struct{}

func (v MyKeyValidator) ValidateKey(key string, keyNode *yaml.Node, path string, ctx *ValidationContext) {
    if strings.HasPrefix(key, "_") {
        ctx.AddError(ValidationError{
            Level:   LevelWarning,
            Path:    path,
            Line:    keyNode.Line,
            Column:  keyNode.Column,
            Message: "keys starting with underscore are reserved",
            Got:     key,
        })
    }
}

Custom validators may be invoked concurrently when the same compiled validator is reused by multiple goroutines. Keep validator state immutable or synchronize it explicitly. Built-in validators snapshot their configuration during CompileFieldSchema; a configurable custom validator can opt into the same behavior by implementing ValueValidatorCloner or KeyValidatorCloner. For cancellable I/O or other blocking work, propagate ctx.Context().

When a custom validator reports an error for a child node, use AppendPropertyPath and AppendIndexPath instead of concatenating strings manually. They preserve unambiguous paths for property names containing dots, brackets, or numeric-looking names.

Best Practices

1. Use AdditionalProperties for arbitrary keys
// Allow any string values for unknown keys
labels: {
    Type:                 TypeMap,
    AdditionalProperties: &FieldSchema{Type: TypeString},
}
2. Combine with key validators
labels: {
    Type:                 TypeMap,
    AdditionalProperties: &FieldSchema{Type: TypeString},
    KeyValidators: []KeyValidator{
        RegexKeyValidator{Pattern: regexp.MustCompile(`^[a-z][a-z0-9._-]*$`)},
    },
}
3. Use Nullable for optional fields that can be explicitly null
timeout: {
    Type:     TypeInt,
    Nullable: true, // Allows: timeout: null
}
4. Use helper functions for pointers
MinItems: Ptr[int](1)
Max:      Ptr[float64](100)

API Reference

Validator
// Preferred for native schemas assembled dynamically
v, err := CompileFieldSchema(schema)

// Backwards-compatible constructor for an already trusted schema
v := NewValidator(schema)

// Validate bytes
result := v.ValidateBytes(yamlData)

// Validate with options
result := v.ValidateWithOptions(yamlData, ValidationContext{...})

// Context-aware validation
result, err := v.ValidateContext(ctx, yamlData)
result, err := v.ValidateContextWithOptions(ctx, yamlData, ValidationContext{...})

// Reader-based validation. MaxBytes reads at most MaxBytes+1 bytes.
result, err := v.ValidateReader(reader)
result, err := v.ValidateReaderWithOptions(reader, ValidationContext{...})
result, err := v.ValidateReaderContext(ctx, reader)
result, err := v.ValidateReaderContextWithOptions(ctx, reader, ValidationContext{...})
ValidationResult
result.HasErrors()              // bool
result.Collector.Errors()       // []ValidationError
result.Collector.Warnings()     // []ValidationError
result.Collector.All()          // []ValidationError in collection order
result.SortByPosition()         // Sort by line/column
result.FormatAll(sortByPos)     // Format with source context
result.Truncated                // true if MaxDiagnostics stopped validation
result.Canceled                 // true if context canceled/deadline expired
result.ContextErr               // context.Canceled / context.DeadlineExceeded
ValidationError
type ValidationError struct {
    Level      ErrorLevel
    Code       string      // Machine-readable code, e.g. "required" or "minimum"
    SchemaPath string      // Originating JSON Schema location when available
    Path       string      // Stable display path, e.g. "spec.containers[0].image"
    PathTokens []PathToken // Typed property/index/document components
    Line       int         // 1-based (0 if unknown)
    Column     int         // 1-based (0 if unknown)
    Message    string
    Got        string
    Expected   string
    Details    any         // Optional typed machine-readable details
}

Details is populated where a diagnostic has useful structured data. Current detail types include RequiredDetails, UnknownKeyDetails, TypeMismatchDetails, NumericRangeDetails, ItemCountDetails, and DependencyDetails. PathTokens avoids parsing the human-readable Path; the leading doc[N] syntax is reserved for multi-document YAML and is represented by PathTokenDocument.

The collector accessors return defensive copies, so callers may sort or modify returned diagnostics without mutating the stored validation result.

Benchmarks

The repository contains both validation-engine benchmarks and a reproducible runtime-vs-generated codec suite.

On an Apple M4 Max / Go 1.26.1 fixture, generated yaml.Node encoding was about 12.4–13.5× faster than reflective node encoding, while generated node decoding was about 15–21% faster. Complete validated Unmarshal improved by about 2–6% because YAML parsing and validation dominate the total cost. The source-aware high-level Marshal path is near parity with the reflective validated path because it intentionally validates the exact emitted bytes; the standard yaml.v3 generated hook was about 28–38% faster than the reflective validated Marshal in the same fixture.

These are measurements of the checked-in fixture, not universal throughput guarantees. In particular, do not interpret the 12–13× node-encoder result as a 12–13× speedup for the complete validated pipeline.

Run the generated-code suite:

go test -mod=readonly -run '^$' \
  -bench '^Benchmark(Unmarshal|Marshal|NodeCodec)$' \
  -benchmem -benchtime=1s -count=5 ./benchmarks

The exact machine, methodology, medians, allocations, and interpretation are recorded in benchmarks/results/2026-09-28-m4-max.md.

The native/JSON Schema engine benchmarks remain available with:

go test -run '^$' -bench='Benchmark(Native|JSONSchema)' -benchmem .

API stability

v1.0.0 established the SemVer-stable v1 line. v1.1.0 adds high-level struct-tag validation and optional typed code generation without changing the application-facing names or call signatures from v1. Existing low-level FieldSchema, Validator, JSON Schema, diagnostics, and extension APIs remain available.

Agent skill and Claude Code plugin

The repository includes an agent skill for integrating the library in Go projects. It covers high-level yamlvalidate struct tags, optional yamlvalidator-gen code generation, native FieldSchema, JSON Schema, source-aware diagnostics, custom validators and extensions, resolvers, CLI usage, and table-driven executable recipes.

For a local Claude Code session:

claude --plugin-dir /absolute/path/to/go-yamlvalidator

Invoke /go-yamlvalidator:go-yamlvalidator, or install the standalone skill with npx skills add Yakwilik/go-yamlvalidator. Agent installation is separate from adding the Go module to an application.

See plugin setup and verification for packaging details, standalone example checks and a candidate marketplace entry. The plugin version is independent of the library version; adding it here does not publish it to an external marketplace.

License

Apache License 2.0

Documentation

Overview

Package yamlvalidator validates YAML against native schemas and Go struct tags. Its public API is a facade over the shared internal validation engine.

Index

Constants

View Source
const (
	// FieldNamingYAML uses yaml.v3's lowercase default names.
	FieldNamingYAML = engine.FieldNamingYAML
	// FieldNamingGo preserves Go field names unless a YAML tag names the field.
	FieldNamingGo = engine.FieldNamingGo
)
View Source
const JSONSchemaDraft2019 = engine.JSONSchemaDraft2019
View Source
const JSONSchemaDraft2020 = engine.JSONSchemaDraft2020
View Source
const JSONSchemaDraft4 = engine.JSONSchemaDraft4
View Source
const JSONSchemaDraft6 = engine.JSONSchemaDraft6
View Source
const JSONSchemaDraft7 = engine.JSONSchemaDraft7
View Source
const LevelError = engine.LevelError

LevelError indicates a critical validation failure.

View Source
const LevelWarning = engine.LevelWarning

LevelWarning indicates a non-critical issue (e.g., deprecated field, unknown key in permissive mode).

View Source
const PathTokenDocument = engine.PathTokenDocument

PathTokenDocument represents the reserved leading doc[N] prefix used for multi-document YAML diagnostics.

View Source
const PathTokenIndex = engine.PathTokenIndex
View Source
const PathTokenProperty = engine.PathTokenProperty
View Source
const TypeAny = engine.TypeAny

TypeAny accepts any type.

View Source
const TypeBool = engine.TypeBool

TypeBool represents boolean values.

View Source
const TypeFloat = engine.TypeFloat

TypeFloat represents floating-point values (also accepts int).

View Source
const TypeInt = engine.TypeInt

TypeInt represents integer values.

View Source
const TypeMap = engine.TypeMap

TypeMap represents mapping nodes.

View Source
const TypeNull = engine.TypeNull

TypeNull represents null/nil values.

View Source
const TypeSequence = engine.TypeSequence

TypeSequence represents sequence/array nodes.

View Source
const TypeString = engine.TypeString

TypeString represents string values.

View Source
const UnknownKeyError = engine.UnknownKeyError

UnknownKeyError treats unknown keys as errors.

View Source
const UnknownKeyIgnore = engine.UnknownKeyIgnore

UnknownKeyIgnore silently ignores unknown keys.

View Source
const UnknownKeyInherit = engine.UnknownKeyInherit

UnknownKeyInherit uses ctx.StrictKeys to decide:

StrictKeys=true  -> error
StrictKeys=false -> warning
View Source
const UnknownKeyWarn = engine.UnknownKeyWarn

UnknownKeyWarn treats unknown keys as warnings.

Variables

View Source
var ErrJSONSchemaResourceNotFound = engine.ErrJSONSchemaResourceNotFound

ErrJSONSchemaResourceNotFound allows resolver chains to distinguish a miss from an actual resolver failure.

View Source
var ErrJSONSchemaResourceOutsideRoot = engine.ErrJSONSchemaResourceOutsideRoot

ErrJSONSchemaResourceOutsideRoot is returned by JSONSchemaFileResolver when a file URL escapes its configured root.

Functions

func AppendIndexPath added in v0.6.0

func AppendIndexPath(base string, index int) (string, error)

AppendIndexPath appends a non-negative sequence index to a stable display path. It returns an error for negative indexes.

func AppendPropertyPath added in v0.6.0

func AppendPropertyPath(base, property string) string

AppendPropertyPath appends a mapping property to a stable display path. Ambiguous property names are quoted automatically.

func FormatErrorWithSource

func FormatErrorWithSource(err ValidationError, lines []string) string

FormatErrorWithSource formats an error with source context. Correctly handles tabs and Unicode.

func FormatPathTokens added in v0.4.0

func FormatPathTokens(tokens []PathToken) string

FormatPathTokens formats typed path tokens using the library's stable display syntax.

func Marshal added in v1.1.0

func Marshal(in any) ([]byte, error)

Marshal encodes and validates a Go value, returning the exact validated bytes.

func Ptr

func Ptr[T any](v T) *T

Ptr returns a pointer to the value. Useful for setting Min/Max fields.

func RenderLineWithCaret

func RenderLineWithCaret(line string, byteCol int) (string, int, int)

RenderLineWithCaret is an exported wrapper useful for external tests and tools.

func Unmarshal added in v1.1.0

func Unmarshal(data []byte, out any) error

Unmarshal decodes one YAML document after validating it.

func ValidateFieldSchema added in v0.3.0

func ValidateFieldSchema(schema *FieldSchema) error

ValidateFieldSchema checks FieldSchema invariants, including nested schemas, invalid constraints, non-progressing recursion, and validator definitions.

Types

type ConditionalRule

type ConditionalRule = engine.ConditionalRule

ConditionalRule defines conditional validation logic. When ConditionField equals ConditionValue, additional requirements apply.

type DefinitionValidator added in v0.3.0

type DefinitionValidator = engine.DefinitionValidator

DefinitionValidator may be implemented by value/key validators that can validate their own configuration during FieldSchema compilation.

type DependencyDetails added in v0.4.0

type DependencyDetails = engine.DependencyDetails

DependencyDetails describes a field required by another field.

type ErrorCollector

type ErrorCollector = engine.ErrorCollector

ErrorCollector accumulates validation errors and warnings.

func NewErrorCollector

func NewErrorCollector() *ErrorCollector

NewErrorCollector creates a new empty ErrorCollector.

type ErrorLevel

type ErrorLevel = engine.ErrorLevel

ErrorLevel defines the severity of a validation error.

type FieldNaming added in v1.2.0

type FieldNaming = engine.FieldNaming

FieldNaming selects the default name of exported Go fields in YAML.

type FieldSchema

type FieldSchema = engine.FieldSchema

FieldSchema defines the validation rules for a field.

func CompileJSONSchema added in v0.3.0

func CompileJSONSchema(data []byte) (*FieldSchema, error)

CompileJSONSchema compiles a JSON Schema using draft 2020-12 as the default dialect. Schemas declaring $schema are compiled using their declared dialect.

func CompileJSONSchemaContext added in v0.5.0

func CompileJSONSchemaContext(ctx context.Context, data []byte) (*FieldSchema, error)

CompileJSONSchemaContext is the context-aware form of CompileJSONSchema. Context cancellation is observed by library-controlled compilation work and by JSONSchemaResolver implementations.

func CompileJSONSchemaContextWithOptions added in v0.5.0

func CompileJSONSchemaContextWithOptions(
	ctx context.Context,
	data []byte,
	opts JSONSchemaCompileOptions,
) (*FieldSchema, error)

CompileJSONSchemaContextWithOptions is the context-aware form of CompileJSONSchemaWithOptions.

func CompileJSONSchemaWithOptions added in v0.3.0

func CompileJSONSchemaWithOptions(data []byte, opts JSONSchemaCompileOptions) (*FieldSchema, error)

CompileJSONSchemaWithOptions compiles a standards-compliant JSON Schema and returns a FieldSchema adapter that validates YAML through the JSON Schema engine while preserving YAML source positions in diagnostics.

type ItemCountDetails added in v0.4.0

type ItemCountDetails = engine.ItemCountDetails

ItemCountDetails describes a sequence length failure.

type JSONSchemaCachingResolver added in v0.5.0

type JSONSchemaCachingResolver = engine.JSONSchemaCachingResolver

JSONSchemaCachingResolver caches successful resolutions. Returned byte slices are defensive copies.

func NewJSONSchemaCachingResolver added in v0.5.0

func NewJSONSchemaCachingResolver(resolver JSONSchemaResolver) *JSONSchemaCachingResolver

NewJSONSchemaCachingResolver wraps resolver with a concurrency-safe cache.

type JSONSchemaCompileOptions added in v0.3.0

type JSONSchemaCompileOptions = engine.JSONSchemaCompileOptions

JSONSchemaCompileOptions controls JSON Schema compilation and validation.

type JSONSchemaContentEncoding added in v0.6.0

type JSONSchemaContentEncoding = engine.JSONSchemaContentEncoding

JSONSchemaContentEncoding registers a custom JSON Schema contentEncoding.

type JSONSchemaContentMediaType added in v0.6.0

type JSONSchemaContentMediaType = engine.JSONSchemaContentMediaType

JSONSchemaContentMediaType registers a custom JSON Schema contentMediaType. UnmarshalJSON is optional and should be set only when the media type contains a JSON-compatible data model that contentSchema may validate.

type JSONSchemaDraft added in v0.3.0

type JSONSchemaDraft = engine.JSONSchemaDraft

JSONSchemaDraft selects the default JSON Schema dialect used when a schema does not declare $schema. An explicit $schema in the document takes precedence.

type JSONSchemaFileResolver added in v0.5.0

type JSONSchemaFileResolver = engine.JSONSchemaFileResolver

JSONSchemaFileResolver resolves file:// resources confined to one directory. The root must exist when the resolver is created.

func NewJSONSchemaFileResolver added in v0.5.0

func NewJSONSchemaFileResolver(root string) (*JSONSchemaFileResolver, error)

NewJSONSchemaFileResolver creates a file resolver constrained to root.

type JSONSchemaFormat added in v0.3.0

type JSONSchemaFormat = engine.JSONSchemaFormat

JSONSchemaFormat registers a custom JSON Schema format without exposing the underlying JSON Schema engine API.

type JSONSchemaKeyword added in v0.3.0

type JSONSchemaKeyword = engine.JSONSchemaKeyword

JSONSchemaKeyword defines one custom JSON Schema keyword. Set exactly one of Validate, Compile, or CompileWithContext. Subschemas declares locations of nested schemas relative to the keyword value.

type JSONSchemaKeywordCompileContext added in v0.5.0

type JSONSchemaKeywordCompileContext = engine.JSONSchemaKeywordCompileContext

JSONSchemaKeywordCompileContext exposes high-level helpers needed by custom keywords which contain nested schemas.

type JSONSchemaKeywordCompileContextFunc added in v0.5.0

type JSONSchemaKeywordCompileContextFunc = engine.JSONSchemaKeywordCompileContextFunc

JSONSchemaKeywordCompileContextFunc is the advanced high-level compile form for keywords that contain nested schemas or schema references.

type JSONSchemaKeywordCompileFunc added in v0.3.0

type JSONSchemaKeywordCompileFunc = engine.JSONSchemaKeywordCompileFunc

JSONSchemaKeywordCompileFunc compiles a keyword value from the schema into a runtime validation function. It is useful for parsing/validating keyword configuration once instead of on every validation call.

type JSONSchemaKeywordFunc added in v0.3.0

type JSONSchemaKeywordFunc = engine.JSONSchemaKeywordFunc

JSONSchemaKeywordFunc is the simple custom-keyword form. The schema keyword value and current JSON instance value are supplied on each validation call.

type JSONSchemaKeywordValidateFunc added in v0.3.0

type JSONSchemaKeywordValidateFunc = engine.JSONSchemaKeywordValidateFunc

JSONSchemaKeywordValidateFunc validates one JSON instance value.

type JSONSchemaKeywordValidationContext added in v0.3.0

type JSONSchemaKeywordValidationContext = engine.JSONSchemaKeywordValidationContext

JSONSchemaKeywordValidationContext collects custom keyword diagnostics and evaluation annotations during one keyword validation call.

type JSONSchemaResolver added in v0.5.0

type JSONSchemaResolver = engine.JSONSchemaResolver

JSONSchemaResolver resolves an absolute JSON Schema retrieval URL. Implementations must be safe for concurrent use if a compile configuration is reused concurrently.

type JSONSchemaResolverChain added in v0.5.0

type JSONSchemaResolverChain = engine.JSONSchemaResolverChain

JSONSchemaResolverChain tries resolvers in order. Only ErrJSONSchemaResourceNotFound advances to the next resolver. Treat the slice as immutable while it is in use.

type JSONSchemaResolverFunc added in v0.5.0

type JSONSchemaResolverFunc = engine.JSONSchemaResolverFunc

JSONSchemaResolverFunc adapts a function to JSONSchemaResolver.

type JSONSchemaResourceMap added in v0.5.0

type JSONSchemaResourceMap = engine.JSONSchemaResourceMap

JSONSchemaResourceMap is an in-memory resolver keyed by absolute retrieval URL. Treat the map as immutable while it is in use; resolved byte slices are copied.

type JSONSchemaSubschema added in v0.5.0

type JSONSchemaSubschema = engine.JSONSchemaSubschema

JSONSchemaSubschema is a compiled nested schema used by custom keywords. Its implementation is intentionally opaque so callers do not depend on the underlying JSON Schema engine.

type JSONSchemaSubschemaPath added in v0.5.0

type JSONSchemaSubschemaPath = engine.JSONSchemaSubschemaPath

JSONSchemaSubschemaPath declares a nested schema location relative to a custom keyword value.

type JSONSchemaSubschemaPosition added in v0.5.0

type JSONSchemaSubschemaPosition = engine.JSONSchemaSubschemaPosition

JSONSchemaSubschemaPosition identifies one possible nested-schema location inside a custom keyword value. Use the constructor functions below.

func JSONSchemaSubschemaAllItems added in v0.5.0

func JSONSchemaSubschemaAllItems() JSONSchemaSubschemaPosition

JSONSchemaSubschemaAllItems selects all array items.

func JSONSchemaSubschemaAllProperties added in v0.5.0

func JSONSchemaSubschemaAllProperties() JSONSchemaSubschemaPosition

JSONSchemaSubschemaAllProperties selects all object property values.

func JSONSchemaSubschemaItem added in v0.5.0

func JSONSchemaSubschemaItem(index int) JSONSchemaSubschemaPosition

JSONSchemaSubschemaItem selects one array item.

func JSONSchemaSubschemaProperty added in v0.5.0

func JSONSchemaSubschemaProperty(name string) JSONSchemaSubschemaPosition

JSONSchemaSubschemaProperty selects one object property.

type JSONSchemaVocabulary added in v0.3.0

type JSONSchemaVocabulary = engine.JSONSchemaVocabulary

JSONSchemaVocabulary groups custom keywords under a vocabulary URL. Vocabularies registered through JSONSchemaCompileOptions are activated for that compilation.

type KeyValidator

type KeyValidator = engine.KeyValidator

KeyValidator validates key names in mappings. The same concurrency contract as ValueValidator applies to stateful implementations.

type KeyValidatorCloner added in v0.4.0

type KeyValidatorCloner = engine.KeyValidatorCloner

KeyValidatorCloner is the key-validator counterpart of ValueValidatorCloner.

type KeyValidatorFactory added in v1.1.0

type KeyValidatorFactory = engine.KeyValidatorFactory

KeyValidatorFactory builds a key validator from structured tag arguments.

type Limits added in v1.1.0

type Limits = engine.Limits

Limits bounds high-level validation work. A zero field selects its default.

type MarshalOptions added in v1.1.0

type MarshalOptions = engine.MarshalOptions

MarshalOptions controls validated YAML encoding. Its zero value enables validation.

type NodeType

type NodeType = engine.NodeType

NodeType represents the expected YAML node type.

func InferNodeType added in v0.6.0

func InferNodeType(node *yaml.Node, ctx *ValidationContext) NodeType

InferNodeType applies the same YAML type inference used by FieldSchema validation. A nil context uses default type-inference settings.

type NumericRangeDetails added in v0.4.0

type NumericRangeDetails = engine.NumericRangeDetails

NumericRangeDetails describes a numeric bound failure.

type PathToken added in v0.4.0

type PathToken = engine.PathToken

PathToken is one typed component of ValidationError.Path.

func ParsePathTokens added in v0.4.0

func ParsePathTokens(path string) ([]PathToken, error)

ParsePathTokens parses the library's display path syntax into typed tokens.

type PathTokenKind added in v0.4.0

type PathTokenKind = engine.PathTokenKind

PathTokenKind identifies one component of a structured validation path.

type Registry added in v1.1.0

type Registry = engine.Registry

Registry is an immutable collection of high-level schema extensions.

func NewRegistry added in v1.1.0

func NewRegistry(config RegistryConfig) (*Registry, error)

NewRegistry snapshots and validates the supplied registry configuration.

type RegistryConfig added in v1.1.0

type RegistryConfig = engine.RegistryConfig

RegistryConfig declares named validation extensions. The constructor takes a snapshot of its maps, slices, and cloneable validators.

type RequiredDetails added in v0.4.0

type RequiredDetails = engine.RequiredDetails

RequiredDetails describes a missing required field/property.

type SchemaError added in v1.1.0

type SchemaError = engine.SchemaError

SchemaError describes an invalid Go type, field, or validation declaration.

type TypeBinding added in v1.1.0

type TypeBinding = engine.TypeBinding

TypeBinding supplies a schema for a type whose YAML representation cannot be inferred safely. Encode and Decode may differ.

type TypeMismatchDetails added in v0.4.0

type TypeMismatchDetails = engine.TypeMismatchDetails

TypeMismatchDetails describes a type validation failure.

type UnknownKeyDetails added in v0.4.0

type UnknownKeyDetails = engine.UnknownKeyDetails

UnknownKeyDetails describes an unknown mapping key and optional suggestion.

type UnknownKeyPolicy

type UnknownKeyPolicy = engine.UnknownKeyPolicy

UnknownKeyPolicy determines how unknown keys in maps are handled.

type UnmarshalOptions added in v1.1.0

type UnmarshalOptions = engine.UnmarshalOptions

UnmarshalOptions controls validated YAML decoding. Its zero value enables validation.

type ValidationContext

type ValidationContext = engine.ValidationContext

ValidationContext holds configuration and state for a validation run.

func NewValidationContext

func NewValidationContext() *ValidationContext

NewValidationContext creates a new ValidationContext with default settings.

type ValidationError

type ValidationError = engine.ValidationError

ValidationError represents a single validation issue.

type ValidationErrors added in v1.1.0

type ValidationErrors = engine.ValidationErrors

ValidationErrors groups the final diagnostics from one high-level operation.

type ValidationResult

type ValidationResult = engine.ValidationResult

ValidationResult contains the validation outcome and context for formatting.

type Validator

type Validator = engine.Validator

Validator performs YAML validation against a schema.

func CompileFieldSchema added in v0.3.0

func CompileFieldSchema(schema *FieldSchema) (*Validator, error)

CompileFieldSchema validates a native FieldSchema before constructing a Validator. New code should prefer this over NewValidator when schemas are assembled dynamically or loaded from configuration.

func NewValidator

func NewValidator(schema *FieldSchema) *Validator

NewValidator creates a Validator that references the supplied schema directly. Callers must not mutate that schema concurrently with validation. Prefer CompileFieldSchema when an immutable, concurrency-safe schema snapshot is desired.

type ValueValidator

type ValueValidator = engine.ValueValidator

ValueValidator validates a node's value. Validator instances may be reused concurrently; custom implementations that keep mutable state must therefore provide their own synchronization.

type ValueValidatorCloner added in v0.4.0

type ValueValidatorCloner = engine.ValueValidatorCloner

ValueValidatorCloner can be implemented by stateful/configurable custom validators so CompileFieldSchema can snapshot their configuration.

type ValueValidatorFactory added in v1.1.0

type ValueValidatorFactory = engine.ValueValidatorFactory

ValueValidatorFactory builds a validator from structured tag arguments. Numeric arguments are json.Number values, preserving their exact spelling.

Directories

Path Synopsis
benchmarks
cmd
yamlvalidator command
yamlvalidator-gen command
Command yamlvalidator-gen generates typed YAML node codecs for selected Go types.
Command yamlvalidator-gen generates typed YAML node codecs for selected Go types.
examples
advanced command
basic command
Example demonstrates how to use the yamlvalidator package to validate Kubernetes-like manifests with comprehensive schema definitions.
Example demonstrates how to use the yamlvalidator package to validate Kubernetes-like manifests with comprehensive schema definitions.
codegen command
highlevel command
tagrules
Package tagrules demonstrates native cross-field validation declarations.
Package tagrules demonstrates native cross-field validation declarations.
Package genruntime contains the runtime ABI used by yamlvalidator-gen output.
Package genruntime contains the runtime ABI used by yamlvalidator-gen output.
spec
Package spec defines the generated schema blueprints shared by yamlvalidator-gen and the private native schema materializer.
Package spec defines the generated schema blueprints shared by yamlvalidator-gen and the private native schema materializer.
internal
checks
Package checks contains calculation primitives shared by the native validators and the high-level tag adapters.
Package checks contains calculation primitives shared by the native validators and the high-level tag adapters.
engine
Package yamlvalidator provides a flexible YAML validation library with support for type checking, custom validators, conditional logic, and detailed error reporting with source context.
Package yamlvalidator provides a flexible YAML validation library with support for type checking, custom validators, conditional logic, and detailed error reporting with source context.
schemacompiler
Package schemacompiler is the generation-time entry to native tag lowering.
Package schemacompiler is the generation-time entry to native tag lowering.
thirdparty/xnet/idna
Package idna implements IDNA2008 using the compatibility processing defined by UTS (Unicode Technical Standard) #46, which defines a standard to deal with the transition from IDNA2003.
Package idna implements IDNA2008 using the compatibility processing defined by UTS (Unicode Technical Standard) #46, which defines a standard to deal with the transition from IDNA2003.
thirdparty/xtext/secure/bidirule
Package bidirule implements the Bidi Rule defined by RFC 5893.
Package bidirule implements the Bidi Rule defined by RFC 5893.
thirdparty/xtext/transform
Package transform provides reader and writer wrappers that transform the bytes passing through as well as various transformations.
Package transform provides reader and writer wrappers that transform the bytes passing through as well as various transformations.
thirdparty/xtext/unicode/bidi
Package bidi contains functionality for bidirectional text support.
Package bidi contains functionality for bidirectional text support.
thirdparty/xtext/unicode/norm
Package norm contains types and functions for normalizing Unicode strings.
Package norm contains types and functions for normalizing Unicode strings.
pkg
skills

Jump to

Keyboard shortcuts

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