diff --git a/src/docs/data-configuration.md b/src/docs/data-configuration.md index 03c492e086..66ddfe80df 100644 --- a/src/docs/data-configuration.md +++ b/src/docs/data-configuration.md @@ -17,6 +17,7 @@ There are a few special data keys you can assign in your data to control how tem - `templateEngineOverride`: Override the template engine on a per-file basis. [Read more about Changing a Template’s Rendering Engine](/docs/languages/#overriding-the-template-language). [_This option only works in Front Matter ⚠️ (for now), read Issue #445_](https://github.com/11ty/eleventy/issues/445). - `eleventyExcludeFromCollections`: {% addedin "0.8.0" %} Set to `true` to exclude this content from any and all [Collections](/docs/collections/) (those tagged in data or setup using the Configuration API). - `eleventyComputed`: {% addedin "0.11.0" %} Programmatically set data values based on other values in your data cascade. Read more about [Computed Data](/docs/data-computed/). +- `eleventyDataSchema`: Used to [validate data](/docs/data-validate/) in the data cascade. - `eleventyNavigation`: Used by the [Navigation plugin](/docs/plugins/navigation/#adding-templates-to-the-navigation). ## Advanced diff --git a/src/docs/data-validate.md b/src/docs/data-validate.md new file mode 100644 index 0000000000..14b76fa5bb --- /dev/null +++ b/src/docs/data-validate.md @@ -0,0 +1,34 @@ +--- +eleventyNavigation: + parent: Data Cascade + key: Validate Data + order: 6 +--- +# Validate Data + +Use the special `eleventyDataSchema` data property to validate data in your Data Cascade. You can set this anywhere in your Data Cascade (front matter, directory data file, global data, etc). + +You can use any schema or validation library to achieve this. In this example, we’re using [`zod`](https://zod.dev/). + +## Example: Checking that `draft` is boolean + +In the following example, each content template with an `eleventyDataSchema` callback (in this example, any templates in the `blog` folder) is checked to make sure the value of any `draft` assignments must be `boolean` or `undefined`. If not, we throw an error. + +
blog/blog.11tydata.js
+ +```js +import { z } from "zod"; +import { fromZodError } from 'zod-validation-error'; + +export default { + eleventyDataSchema: function(data) { + let result = z.object({ + draft: z.boolean().or(z.undefined()), + }).safeParse(data); + + if(result.error) { + throw fromZodError(result.error); + } + } +}; +``` \ No newline at end of file