Validador YAML
Valide sintaxe e estrutura YAML com relatório detalhado de erros
What is YAML Validation?
YAML validation is the process of verifying whether a document conforms to the YAML 1.2.2 specification grammar and structural rules. Unlike formatting — which adjusts indentation and style for readability — validation answers a fundamental question: is this document well-formed YAML that a parser can process without errors? When validation fails, detailed error diagnostics including line numbers, error types, and descriptions help you locate and fix problems before they cause deployment failures or application crashes. This tool performs strict parsing against the YAML specification and reports every syntax violation it encounters.
YAML Syntax Rules and Validation Scope
The YAML 1.2.2 specification defines a context-sensitive grammar where whitespace is semantically significant. YAML validation checks that a document is well-formed — meaning it can be successfully parsed into the intended data structure. The validation scope covers structural correctness, proper indentation, valid character usage, and conformance to the serialization model:
- Indentation must use spaces only: Tab characters (U+0009) are forbidden in YAML indentation. Every indentation level must consist exclusively of space characters (U+0020). Mixing tabs and spaces is the single most common cause of YAML parsing failures, especially when copying content between editors with different tab settings.
- Consistent indentation within a block: All items at the same nesting level must use identical indentation. If a mapping starts at column 2, all its keys must also begin at column 2. Inconsistent indentation produces ambiguous structures that parsers reject.
- Proper mapping syntax: Mapping keys must be followed by a colon and at
least one space (
key: value). Omitting the space after the colon (key:value) causes the entire string to be interpreted as a scalar, not a key-value pair. - Duplicate keys are forbidden: The YAML 1.2.2 specification explicitly states that mapping keys must be unique within a single mapping node. Duplicate keys produce undefined behavior — different parsers may keep the first value, the last value, or reject the document entirely.
- Proper quoting for special characters: Strings containing characters like
:,#,[,{, or leading*and&must be quoted to prevent misinterpretation as YAML syntax elements such as anchors, aliases, comments, or flow collections. - Document markers: Multi-document streams use
---to begin a new document and...to explicitly end one. Misplaced markers can split a single intended document into unexpected fragments.
Validation also detects structural issues that go beyond simple syntax: circular references through aliases, invalid UTF-8 byte sequences, byte order mark handling, and conformance to the YAML serialization model where nodes are organized as mappings, sequences, and scalars.
Common YAML Errors Detected by Validation
YAML's whitespace sensitivity and implicit typing create categories of errors that are unique to this format. Understanding these common mistakes helps you write YAML that passes validation on the first attempt:
Tab characters in indentation: This is the most frequent YAML error. Editors may insert tabs when you press the indent key, and the characters are invisible in most views. A validator immediately flags the exact line containing tabs, whereas a failed deployment may only show a cryptic "mapping values are not allowed here" message without pointing to the underlying tab character.
Implicit type coercion ("the Norway problem"): YAML 1.1 parsers interpret
bare values like yes, no, on, off,
true, and false as booleans. Country codes like NO
(Norway), version strings like 1.0 (interpreted as a float), and timestamps
like 2024-01-01 can be silently converted to unexpected types. Validation with
strict mode flags these ambiguous scalars so you can add explicit quotes where needed.
Incorrect sequence indentation: Sequence items (lines starting with
-) must be indented consistently. A common mistake is aligning the dash with
the parent key instead of indenting it further, which changes the parsed structure. For
example, placing a dash at the same column as its parent key makes it a sibling rather
than a child element.
Unquoted strings with special characters: Values containing colons followed
by spaces (like message: Error: file not found) are parsed as nested mappings
unless quoted. URLs, Windows file paths with backslashes, and strings starting with
% or @ are other common sources of parsing failures that
validation catches immediately.
Multiline string indicators: The literal block scalar (|) and
folded block scalar (>) indicators have strict rules about the indentation
of subsequent lines. Content must be indented at least one level deeper than the indicator
line, and the chomping modifier (|-, |+) controls trailing
newline handling.
Error Detection and Reporting
Effective YAML validation goes beyond simply reporting "invalid YAML" — it provides actionable diagnostics that help you fix problems quickly. This validator reports errors with precise location information and contextual descriptions:
Line and column numbers: Every error includes the exact line number and column position where the parser encountered the problem. For indentation errors, the column number directly indicates which character broke the expected alignment. For missing colons or unexpected tokens, the position shows where the parser's expectation diverged from reality.
Error categorization: Errors are classified by type — syntax errors (malformed tokens), structural errors (incorrect nesting or duplicate keys), encoding errors (invalid UTF-8 sequences), and semantic warnings (implicit type coercion risks). This classification helps you prioritize fixes: syntax errors prevent parsing entirely, while semantic warnings indicate potential data integrity issues.
Preventing deployment failures: YAML is the configuration language for Kubernetes manifests, Docker Compose files, GitHub Actions workflows, Ansible playbooks, and CI/CD pipelines. A single indentation error can cause a deployment to fail, a service to misconfigure, or a pipeline to execute incorrectly. Validating YAML before committing to version control catches these issues at the earliest possible stage — in your editor rather than in production. Many teams integrate YAML validation into pre-commit hooks and CI pipelines as a mandatory gate before any configuration change can be merged.
Multi-document validation: YAML files can contain multiple documents
separated by --- markers. The validator checks each document independently
and reports which document number contains the error, preventing confusion in files that
combine multiple Kubernetes resources or configuration sets.
Validation vs Formatting: Understanding the Difference
YAML validation and YAML formatting address fundamentally different concerns, though they are often confused because both involve parsing YAML content. Validation determines correctness: can this document be parsed without errors? Formatting determines style: how should this valid document be presented for human readability?
A validator rejects documents that contain syntax errors — tab characters, duplicate keys, broken indentation, or malformed scalars. Its output is a pass/fail verdict with error diagnostics. A formatter accepts already-valid YAML and adjusts its visual presentation: normalizing indentation width, choosing between block and flow styles, adding or removing blank lines between sections, and sorting keys alphabetically. Formatting cannot fix syntax errors because it requires valid input to operate on.
Use validation when receiving YAML from external sources (APIs, user input, generated templates), when debugging unexpected behavior in configuration files, or as a CI/CD gate. Use formatting when you want consistent style across a team, when preparing configuration for code review, or when converting between compact and expanded representations of valid YAML content.
In practice, validation is the prerequisite step: validate first to confirm correctness, then format to ensure stylistic consistency. Running a formatter on invalid YAML will either produce an error (if the formatter validates internally) or silently corrupt the document structure.
Code Examples
YAML validation: detecting common syntax errors
# ✅ Valid YAML document
apiVersion: apps/v1
kind: Deployment
metadata:
name: web-server
labels:
app: nginx
environment: production
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
spec:
containers:
- name: nginx
image: "nginx:1.25"
ports:
- containerPort: 80
---
# ❌ Invalid: tab character in indentation (line 3)
apiVersion: v1
kind: Service
metadata:
name: web-service # TAB character causes parse failure
# ❌ Invalid: duplicate key (line 4)
database:
host: localhost
port: 5432
port: 3306 # Duplicate key - which port is correct?
# ❌ Invalid: unquoted special characters
message: Error: connection failed # Parsed as nested mapping
path: C:\Users\admin # Backslash needs quoting
# ✅ Fixed versions with proper quoting
message: "Error: connection failed"
path: "C:\\Users\\admin"Programmatic YAML validation with error reporting
import { parse, YAMLError } from 'yaml';
function validateYaml(input) {
const errors = [];
try {
const doc = parse(input, {
strict: true, // Enforce spec compliance
uniqueKeys: true, // Reject duplicate keys
maxAliasCount: 100, // Prevent alias bombs
});
return { valid: true, documents: 1, data: doc };
} catch (error) {
if (error instanceof YAMLError) {
errors.push({
message: error.message,
line: error.linePos?.[0]?.line,
column: error.linePos?.[0]?.col,
type: 'syntax-error'
});
}
return { valid: false, errors };
}
}
// Usage:
validateYaml('name: Alice\nage: 30');
// → { valid: true, documents: 1, data: { name: "Alice", age: 30 } }
validateYaml('items:\n\t- one\n\t- two');
// → { valid: false, errors: [{ message: "Tabs not allowed...",
// line: 2, column: 1, type: "syntax-error" }] }Standards & Specifications
- YAML 1.2.2 Specification — The current YAML specification defining the grammar and serialization rules this validator enforces