Validating LLM Markdown Output: A Production Playbook (2026)
LLMs return Markdown that's usually right and occasionally broken — unbalanced fences, bad tables, skipped headings, dead links. Here's how to validate AI output programmatically before you trust it.
LLM Markdown is usually well-formed — which is exactly why the failures are dangerous. The 1-in-50 response with an unbalanced code fence, a table that doesn't parse, a heading that jumps from H2 to H4, or a confidently hallucinated link will sail through your app and break a page, a PDF export, or a downstream parser. If you display or store AI Markdown, you need to validate it like any other untrusted input.
This is a production playbook: what goes wrong, which checks to run, and how to wire them in with the validate and audit APIs — including what to do when validation fails.
Why validate AI Markdown at all?
Three reasons, in order of severity:
- It breaks rendering. An unterminated
```fence swallows the rest of the document. A malformed pipe table renders as raw text. - It breaks downstream tools. If the Markdown feeds a static site generator, a PDF pipeline, or a parser, structural errors cascade.
- It's a security and trust issue. Hallucinated links, missing alt text, and injected HTML are quality and safety problems. (For the XSS angle specifically, see rendering ChatGPT Markdown safely.)
Validation is cheap insurance: the validate endpoint never renders or modifies the document — it just reports issues with a line, rule, and severity.
What actually goes wrong in LLM Markdown
| Failure | Symptom | Caught by |
|---|---|---|
| Unbalanced code fence | Rest of doc becomes code | GFM audit |
| Fence missing language | No syntax highlighting | GFM audit |
| Malformed pipe table | Renders as raw | text | GFM audit |
| Heading jump (H2→H4) | Broken outline, bad a11y | headings audit |
| Multiple H1s | SEO/structure issue | headings audit |
Missing space after # | ##Heading doesn't render | validate |
| Inconsistent bullets | */-/+ mixed | validate |
| Hallucinated/dead links | 404s in published content | extract links |
| Missing image alt text | Accessibility failure | extract images |
| Trailing whitespace / blank-line spam | Noisy diffs | validate |
The core validation call
async function validateMarkdown(markdown) {
const res = await fetch("https://trymarkdownviewer.com/api/v1/validate", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.MDV_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ markdown }),
});
return (await res.json()).data; // { valid, issueCount, issues: [...] }
}
{
"valid": false,
"issueCount": 2,
"issues": [
{ "line": 1, "message": "Missing space after `#` in heading.", "rule": "heading-space", "severity": "warning" },
{ "line": 12, "message": "Use `-` for unordered list items.", "rule": "consistent-bullets", "severity": "info" }
]
}
Gate on severity — block on error/warning, treat info as cosmetic.
A layered validation pipeline
For production AI features, chain checks by importance and cost:
LLM output
│
├─ 1. validate (fast, always) /api/v1/validate
├─ 2. GFM audit (fences, tables) /api/v1/audit/gfm
├─ 3. headings audit (outline integrity) /api/v1/audit/headings
├─ 4. links/images (dead refs, alt text) /api/v1/extract/{links,images}
└─ 5. render+sanitize (only if all pass) /api/v1/render
async function gateAiMarkdown(markdown) {
const v = await validateMarkdown(markdown);
const blocking = v.issues.filter(i => i.severity !== "info");
if (blocking.length) {
return { ok: false, stage: "validate", issues: blocking };
}
// ...repeat for GFM/headings/links as needed...
return { ok: true };
}
You don't need all five for every use case — pick by where the output goes (a chat bubble needs render-safety; a docs commit needs the full chain).
What to do when validation fails
You have four strategies; choose by context:
| Strategy | When | How |
|---|---|---|
| Auto-fix | Cosmetic issues | Run /api/v1/format to normalize bullets, blank lines, trailing space |
| Regenerate | Structural breakage | Re-prompt the model with the specific issues appended |
| Reject | Safety/quality gate | Block storage/display; log for review |
| Surface | Human-in-the-loop | Show issues in an editor UI for an author to fix |
Self-healing re-prompt
The most effective pattern for structural errors is feeding the validator's output back to the model:
if (!result.ok) {
const issueText = result.issues
.map(i => `- line ${i.line} [${i.rule}]: ${i.message}`)
.join("\n");
const repaired = await llm.chat([
{ role: "assistant", content: markdown },
{ role: "user", content:
`Your Markdown has these issues. Return corrected Markdown only:\n${issueText}` },
]);
}
Because each issue carries a precise line and rule, the model gets actionable feedback and usually fixes it on the second pass.
Validating tool-call and structured output
When the LLM produces Markdown inside a JSON tool response or a structured field:
- Extract the Markdown field.
- Validate it independently (don't trust schema validity to mean Markdown validity).
- For tables specifically, the GFM audit confirms the first table parses; the CSV/table tools can round-trip it to verify structure.
If the model returns JSON that should become Markdown (e.g., an API response to display), the JSON to Markdown tool/endpoint gives you deterministic, always-valid output — sometimes better than asking the model to format the table itself.
Manual spot-checks during development
While building the feature, paste sample model outputs into the browser tools to see failures fast:
- GFM checklist — fences, tables, H1 count.
- Heading audit — outline jumps.
- Link checker — dead/hallucinated links and missing alt text.
- Markdown editor — eyeball the rendered result.
Build a small corpus of real model outputs (including the weird ones) and run them through your gate as regression tests.
Performance and cost
- Validate is fast — a single pass, typically under 30ms for documents under 32 KiB, and it never renders.
- Cache by content hash — identical Markdown always produces identical results.
- Validate before render — it's cheaper than rendering, so use it as a pre-flight to avoid wasted render calls on broken input.
Common mistakes
1. Assuming LLM Markdown is always valid. The rare broken response is the one that breaks production.
2. Validating only for safety. Sanitization (XSS) and validation (structure) are different jobs — do both. See safe HTML rendering.
3. Hard-failing on cosmetic issues. Auto-fix info-level problems with format; don't reject the whole response.
4. No re-prompt loop. Feeding issues back to the model fixes most structural errors automatically.
5. Ignoring links. Hallucinated URLs are a top LLM failure — extract and check them.
Related articles
- Rendering ChatGPT Markdown as safe HTML — the security half
- ChatGPT Markdown formatting guide — cleaner output upstream
- Lint Markdown in CI — same API for docs
- Docs-as-code guide — validation in content pipelines
- Validate API reference
Quick reference
| Check | Endpoint | Catches |
|---|---|---|
| General lint | /api/v1/validate | headings, bullets, whitespace |
| GFM compliance | /api/v1/audit/gfm | fences, tables, H1 |
| Outline | /api/v1/audit/headings | jumps, multi-H1 |
| Links | /api/v1/extract/links | dead/hallucinated URLs |
| Images | /api/v1/extract/images | missing alt text |
| Render (safe) | /api/v1/render | sanitized HTML |
LLM Markdown is untrusted input that looks trustworthy. Validate it before you store or display it, feed failures back to the model to self-heal, and only render once it passes — that's the difference between an AI feature that occasionally breaks and one that holds up in production.
Written by Markdown Viewer Team. Found this useful? Try the editor →
Keep reading
Hand-picked articles related to this one.
LLMs output Markdown. Rendering it naively opens an XSS hole. Here's how to convert ChatGPT, Claude, and Gemini Markdown into sanitized HTML safely — with a hosted API or a hardened local pipeline.
Ship documentation from Git with Markdown — repo structure, Hugo, Docusaurus, MDX, review workflows, CI linting, API automation, and patterns documentation teams use at scale.
Convert Markdown to clean HTML for CMS, email, and static sites — browser tools, CLI, JavaScript libraries, static generators, and API pipelines compared with code examples.