A library for validating YAML documents against a schema.
yaml-schema is a schema validation library that allows you to enforce type safety and structural constraints on YAML files. It works directly with an AST (which can be obtained from Psych) representation to provide strict validation without implicit type coercion.
require "yaml-schema"
schema = {
"type" => "object",
"properties" => {
"name" => { "type" => "string" },
"age" => { "type" => "integer" },
"active" => { "type" => "boolean" }
}
}
yaml_string = <<~YAML
name: "John Doe"
age: 30
active: true
YAML
node = Psych.parse(yaml_string)
YAMLSchema::Validator.validate(schema, node.children.first)- string - Scalar string values
- integer - Numeric integers
- boolean - Boolean values (true/false)
- null - Null values
- array - Sequences with optional constraints
items- Schema for all array elementsprefixItems- Fixed-position tuple validationmaxItems- Maximum array length
- object - Mappings with properties
properties- Named properties with schemasitems- Schema for arbitrary key-value pairstag- Optional YAML tag requirement
Specify multiple valid types for a field:
schema = {
"type" => "object",
"properties" => {
"value" => { "type" => ["null", "string"] }
}
}schema = {
"type" => "object",
"properties" => {
"users" => {
"type" => "array",
"items" => {
"type" => "object",
"properties" => {
"name" => { "type" => "string" },
"tags" => {
"type" => "array",
"items" => { "type" => "string" }
}
}
}
}
}
}Validation errors include detailed path information:
begin
YAMLSchema::Validator.validate(schema, node)
rescue YAMLSchema::Validator::UnexpectedType => e
puts e.message # e.g., "Expected integer at root -> age"
endUnexpectedType- Node doesn't match expected typeUnexpectedProperty- Object has unexpected propertiesUnexpectedTag- YAML tag doesn't match schemaUnexpectedValue- Value doesn't match constraintsInvalidSchema- Schema definition is invalid