> For AI agents: the complete documentation index is available at https://nhanbe.id.vn/llms.txt, the full documentation bundle is available at https://nhanbe.id.vn/llms-full.txt.

# Dialog Validation

AEM's Touch UI dialog framework includes a client-side validation system that lets you enforce business rules **before** an author saves a dialog. This prevents invalid data from reaching the JCR, reduces content errors, and improves the authoring experience by providing immediate, in-dialog feedback.

This guide covers the built-in validation system, how to register custom validators, and a collection of ready-to-use validation examples.

:::info Official documentation

- [Using Validation in Granite UI](https://developer.adobe.com/experience-manager/reference-materials/6-5/granite-ui/api/jcr_root/libs/granite/ui/components/coral/foundation/clientlibs/foundation/js/validation/index.html) - the `foundation.validation` API (`validator`, `selector`, `validate/show/clear`)
- [Granite UI `field` component](https://developer.adobe.com/experience-manager/reference-materials/6-5/granite-ui/api/jcr_root/libs/granite/ui/components/coral/foundation/form/field/index.html) - the `foundation-field` adapter the validators call
- [TextField `validation` attribute](https://developer.adobe.com/experience-manager/reference-materials/6-5/granite-ui/api/jcr_root/libs/granite/ui/components/coral/foundation/form/textfield/index.html) - how a field declares a validator
- [Creating a New Granite UI Field Component](https://experienceleague.adobe.com/en/docs/experience-manager-65-lts/content/implementing/developing/platform/granite-ui-component)

The validation framework is **identical on AEM 6.5 and AEM as a Cloud Service** - the same `foundation-registry` API, the same field attributes, and the same `cq.authoring.dialog` clientlib category. Nothing in this guide is platform-specific.:::

## How Validation Works

<svg id="mermaid-svg-9613216" width="100%" xmlns="http://www.w3.org/2000/svg" style="max-width: 1112px;" viewBox="-50 -10 1112 875" role="graphics-document document" aria-roledescription="sequence"><g><rect x="862" y="789" fill="#eaeaea" stroke="#666" width="150" height="65" name="Validator" rx="3" ry="3"></rect><text x="937" y="821.5" dominant-baseline="central" alignment-baseline="central" style="text-anchor: middle; font-size: 16px; font-weight: 400;" fill="currentColor"><tspan x="937" dy="0">Custom Validator</tspan></text></g> <g><rect x="528" y="789" fill="#eaeaea" stroke="#666" width="162" height="65" name="Registry" rx="3" ry="3"></rect><text x="609" y="821.5" dominant-baseline="central" alignment-baseline="central" style="text-anchor: middle; font-size: 16px; font-weight: 400;" fill="currentColor"><tspan x="609" dy="0">Foundation Registry</tspan></text></g> <g><rect x="255" y="789" fill="#eaeaea" stroke="#666" width="150" height="65" name="Dialog" rx="3" ry="3"></rect><text x="330" y="821.5" dominant-baseline="central" alignment-baseline="central" style="text-anchor: middle; font-size: 16px; font-weight: 400;" fill="currentColor"><tspan x="330" dy="0">Dialog UI</tspan></text></g> <g><rect x="0" y="789" fill="#eaeaea" stroke="#666" width="150" height="65" name="Author" rx="3" ry="3"></rect><text x="75" y="821.5" dominant-baseline="central" alignment-baseline="central" style="text-anchor: middle; font-size: 16px; font-weight: 400;" fill="currentColor"><tspan x="75" dy="0">Author</tspan></text></g> <g><line id="actor13" x1="937" y1="65" x2="937" y2="789" stroke-width="0.5px" stroke="#999" name="Validator" data-et="life-line" data-id="Validator"></line><g id="root-13" data-et="participant" data-type="participant" data-id="Validator"><rect x="862" y="0" fill="#eaeaea" stroke="#666" width="150" height="65" name="Validator" rx="3" ry="3"></rect><text x="937" y="32.5" dominant-baseline="central" alignment-baseline="central" style="text-anchor: middle; font-size: 16px; font-weight: 400;" fill="currentColor"><tspan x="937" dy="0">Custom Validator</tspan></text></g></g> <g><line id="actor12" x1="609" y1="65" x2="609" y2="789" stroke-width="0.5px" stroke="#999" name="Registry" data-et="life-line" data-id="Registry"></line><g id="root-12" data-et="participant" data-type="participant" data-id="Registry"><rect x="528" y="0" fill="#eaeaea" stroke="#666" width="162" height="65" name="Registry" rx="3" ry="3"></rect><text x="609" y="32.5" dominant-baseline="central" alignment-baseline="central" style="text-anchor: middle; font-size: 16px; font-weight: 400;" fill="currentColor"><tspan x="609" dy="0">Foundation Registry</tspan></text></g></g> <g><line id="actor11" x1="330" y1="65" x2="330" y2="789" stroke-width="0.5px" stroke="#999" name="Dialog" data-et="life-line" data-id="Dialog"></line><g id="root-11" data-et="participant" data-type="participant" data-id="Dialog"><rect x="255" y="0" fill="#eaeaea" stroke="#666" width="150" height="65" name="Dialog" rx="3" ry="3"></rect><text x="330" y="32.5" dominant-baseline="central" alignment-baseline="central" style="text-anchor: middle; font-size: 16px; font-weight: 400;" fill="currentColor"><tspan x="330" dy="0">Dialog UI</tspan></text></g></g> <g><line id="actor10" x1="75" y1="65" x2="75" y2="789" stroke-width="0.5px" stroke="#999" name="Author" data-et="life-line" data-id="Author"></line><g id="root-10" data-et="participant" data-type="participant" data-id="Author"><rect x="0" y="0" fill="#eaeaea" stroke="#666" width="150" height="65" name="Author" rx="3" ry="3"></rect><text x="75" y="32.5" dominant-baseline="central" alignment-baseline="central" style="text-anchor: middle; font-size: 16px; font-weight: 400;" fill="currentColor"><tspan x="75" dy="0">Author</tspan></text></g></g> <g></g><defs><symbol id="mermaid-svg-9613216-computer" width="24" height="24"><path transform="scale(.5)" d="M2 2v13h20v-13h-20zm18 11h-16v-9h16v9zm-10.228 6l.466-1h3.524l.467 1h-4.457zm14.228 3h-24l2-6h2.104l-1.33 4h18.45l-1.297-4h2.073l2 6zm-5-10h-14v-7h14v7z"></path></symbol></defs><defs><symbol id="mermaid-svg-9613216-database" fill-rule="evenodd" clip-rule="evenodd"><path transform="scale(.5)" d="M12.258.001l.256.004.255.005.253.008.251.01.249.012.247.015.246.016.242.019.241.02.239.023.236.024.233.027.231.028.229.031.225.032.223.034.22.036.217.038.214.04.211.041.208.043.205.045.201.046.198.048.194.05.191.051.187.053.183.054.18.056.175.057.172.059.168.06.163.061.16.063.155.064.15.066.074.033.073.033.071.034.07.034.069.035.068.035.067.035.066.035.064.036.064.036.062.036.06.036.06.037.058.037.058.037.055.038.055.038.053.038.052.038.051.039.05.039.048.039.047.039.045.04.044.04.043.04.041.04.04.041.039.041.037.041.036.041.034.041.033.042.032.042.03.042.029.042.027.042.026.043.024.043.023.043.021.043.02.043.018.044.017.043.015.044.013.044.012.044.011.045.009.044.007.045.006.045.004.045.002.045.001.045v17l-.001.045-.002.045-.004.045-.006.045-.007.045-.009.044-.011.045-.012.044-.013.044-.015.044-.017.043-.018.044-.02.043-.021.043-.023.043-.024.043-.026.043-.027.042-.029.042-.03.042-.032.042-.033.042-.034.041-.036.041-.037.041-.039.041-.04.041-.041.04-.043.04-.044.04-.045.04-.047.039-.048.039-.05.039-.051.039-.052.038-.053.038-.055.038-.055.038-.058.037-.058.037-.06.037-.06.036-.062.036-.064.036-.064.036-.066.035-.067.035-.068.035-.069.035-.07.034-.071.034-.073.033-.074.033-.15.066-.155.064-.16.063-.163.061-.168.06-.172.059-.175.057-.18.056-.183.054-.187.053-.191.051-.194.05-.198.048-.201.046-.205.045-.208.043-.211.041-.214.04-.217.038-.22.036-.223.034-.225.032-.229.031-.231.028-.233.027-.236.024-.239.023-.241.02-.242.019-.246.016-.247.015-.249.012-.251.01-.253.008-.255.005-.256.004-.258.001-.258-.001-.256-.004-.255-.005-.253-.008-.251-.01-.249-.012-.247-.015-.245-.016-.243-.019-.241-.02-.238-.023-.236-.024-.234-.027-.231-.028-.228-.031-.226-.032-.223-.034-.22-.036-.217-.038-.214-.04-.211-.041-.208-.043-.204-.045-.201-.046-.198-.048-.195-.05-.19-.051-.187-.053-.184-.054-.179-.056-.176-.057-.172-.059-.167-.06-.164-.061-.159-.063-.155-.064-.151-.066-.074-.033-.072-.033-.072-.034-.07-.034-.069-.035-.068-.035-.067-.035-.066-.035-.064-.036-.063-.036-.062-.036-.061-.036-.06-.037-.058-.037-.057-.037-.056-.038-.055-.038-.053-.038-.052-.038-.051-.039-.049-.039-.049-.039-.046-.039-.046-.04-.044-.04-.043-.04-.041-.04-.04-.041-.039-.041-.037-.041-.036-.041-.034-.041-.033-.042-.032-.042-.03-.042-.029-.042-.027-.042-.026-.043-.024-.043-.023-.043-.021-.043-.02-.043-.018-.044-.017-.043-.015-.044-.013-.044-.012-.044-.011-.045-.009-.044-.007-.045-.006-.045-.004-.045-.002-.045-.001-.045v-17l.001-.045.002-.045.004-.045.006-.045.007-.045.009-.044.011-.045.012-.044.013-.044.015-.044.017-.043.018-.044.02-.043.021-.043.023-.043.024-.043.026-.043.027-.042.029-.042.03-.042.032-.042.033-.042.034-.041.036-.041.037-.041.039-.041.04-.041.041-.04.043-.04.044-.04.046-.04.046-.039.049-.039.049-.039.051-.039.052-.038.053-.038.055-.038.056-.038.057-.037.058-.037.06-.037.061-.036.062-.036.063-.036.064-.036.066-.035.067-.035.068-.035.069-.035.07-.034.072-.034.072-.033.074-.033.151-.066.155-.064.159-.063.164-.061.167-.06.172-.059.176-.057.179-.056.184-.054.187-.053.19-.051.195-.05.198-.048.201-.046.204-.045.208-.043.211-.041.214-.04.217-.038.22-.036.223-.034.226-.032.228-.031.231-.028.234-.027.236-.024.238-.023.241-.02.243-.019.245-.016.247-.015.249-.012.251-.01.253-.008.255-.005.256-.004.258-.001.258.001zm-9.258 20.499v.01l.001.021.003.021.004.022.005.021.006.022.007.022.009.023.01.022.011.023.012.023.013.023.015.023.016.024.017.023.018.024.019.024.021.024.022.025.023.024.024.025.052.049.056.05.061.051.066.051.07.051.075.051.079.052.084.052.088.052.092.052.097.052.102.051.105.052.11.052.114.051.119.051.123.051.127.05.131.05.135.05.139.048.144.049.147.047.152.047.155.047.16.045.163.045.167.043.171.043.176.041.178.041.183.039.187.039.19.037.194.035.197.035.202.033.204.031.209.03.212.029.216.027.219.025.222.024.226.021.23.02.233.018.236.016.24.015.243.012.246.01.249.008.253.005.256.004.259.001.26-.001.257-.004.254-.005.25-.008.247-.011.244-.012.241-.014.237-.016.233-.018.231-.021.226-.021.224-.024.22-.026.216-.027.212-.028.21-.031.205-.031.202-.034.198-.034.194-.036.191-.037.187-.039.183-.04.179-.04.175-.042.172-.043.168-.044.163-.045.16-.046.155-.046.152-.047.148-.048.143-.049.139-.049.136-.05.131-.05.126-.05.123-.051.118-.052.114-.051.11-.052.106-.052.101-.052.096-.052.092-.052.088-.053.083-.051.079-.052.074-.052.07-.051.065-.051.06-.051.056-.05.051-.05.023-.024.023-.025.021-.024.02-.024.019-.024.018-.024.017-.024.015-.023.014-.024.013-.023.012-.023.01-.023.01-.022.008-.022.006-.022.006-.022.004-.022.004-.021.001-.021.001-.021v-4.127l-.077.055-.08.053-.083.054-.085.053-.087.052-.09.052-.093.051-.095.05-.097.05-.1.049-.102.049-.105.048-.106.047-.109.047-.111.046-.114.045-.115.045-.118.044-.12.043-.122.042-.124.042-.126.041-.128.04-.13.04-.132.038-.134.038-.135.037-.138.037-.139.035-.142.035-.143.034-.144.033-.147.032-.148.031-.15.03-.151.03-.153.029-.154.027-.156.027-.158.026-.159.025-.161.024-.162.023-.163.022-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.011-.178.01-.179.008-.179.008-.181.006-.182.005-.182.004-.184.003-.184.002h-.37l-.184-.002-.184-.003-.182-.004-.182-.005-.181-.006-.179-.008-.179-.008-.178-.01-.176-.011-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.022-.162-.023-.161-.024-.159-.025-.157-.026-.156-.027-.155-.027-.153-.029-.151-.03-.15-.03-.148-.031-.146-.032-.145-.033-.143-.034-.141-.035-.14-.035-.137-.037-.136-.037-.134-.038-.132-.038-.13-.04-.128-.04-.126-.041-.124-.042-.122-.042-.12-.044-.117-.043-.116-.045-.113-.045-.112-.046-.109-.047-.106-.047-.105-.048-.102-.049-.1-.049-.097-.05-.095-.05-.093-.052-.09-.051-.087-.052-.085-.053-.083-.054-.08-.054-.077-.054v4.127zm0-5.654v.011l.001.021.003.021.004.021.005.022.006.022.007.022.009.022.01.022.011.023.012.023.013.023.015.024.016.023.017.024.018.024.019.024.021.024.022.024.023.025.024.024.052.05.056.05.061.05.066.051.07.051.075.052.079.051.084.052.088.052.092.052.097.052.102.052.105.052.11.051.114.051.119.052.123.05.127.051.131.05.135.049.139.049.144.048.147.048.152.047.155.046.16.045.163.045.167.044.171.042.176.042.178.04.183.04.187.038.19.037.194.036.197.034.202.033.204.032.209.03.212.028.216.027.219.025.222.024.226.022.23.02.233.018.236.016.24.014.243.012.246.01.249.008.253.006.256.003.259.001.26-.001.257-.003.254-.006.25-.008.247-.01.244-.012.241-.015.237-.016.233-.018.231-.02.226-.022.224-.024.22-.025.216-.027.212-.029.21-.03.205-.032.202-.033.198-.035.194-.036.191-.037.187-.039.183-.039.179-.041.175-.042.172-.043.168-.044.163-.045.16-.045.155-.047.152-.047.148-.048.143-.048.139-.05.136-.049.131-.05.126-.051.123-.051.118-.051.114-.052.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.051.07-.052.065-.051.06-.05.056-.051.051-.049.023-.025.023-.024.021-.025.02-.024.019-.024.018-.024.017-.024.015-.023.014-.023.013-.024.012-.022.01-.023.01-.023.008-.022.006-.022.006-.022.004-.021.004-.022.001-.021.001-.021v-4.139l-.077.054-.08.054-.083.054-.085.052-.087.053-.09.051-.093.051-.095.051-.097.05-.1.049-.102.049-.105.048-.106.047-.109.047-.111.046-.114.045-.115.044-.118.044-.12.044-.122.042-.124.042-.126.041-.128.04-.13.039-.132.039-.134.038-.135.037-.138.036-.139.036-.142.035-.143.033-.144.033-.147.033-.148.031-.15.03-.151.03-.153.028-.154.028-.156.027-.158.026-.159.025-.161.024-.162.023-.163.022-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.011-.178.009-.179.009-.179.007-.181.007-.182.005-.182.004-.184.003-.184.002h-.37l-.184-.002-.184-.003-.182-.004-.182-.005-.181-.007-.179-.007-.179-.009-.178-.009-.176-.011-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.022-.162-.023-.161-.024-.159-.025-.157-.026-.156-.027-.155-.028-.153-.028-.151-.03-.15-.03-.148-.031-.146-.033-.145-.033-.143-.033-.141-.035-.14-.036-.137-.036-.136-.037-.134-.038-.132-.039-.13-.039-.128-.04-.126-.041-.124-.042-.122-.043-.12-.043-.117-.044-.116-.044-.113-.046-.112-.046-.109-.046-.106-.047-.105-.048-.102-.049-.1-.049-.097-.05-.095-.051-.093-.051-.09-.051-.087-.053-.085-.052-.083-.054-.08-.054-.077-.054v4.139zm0-5.666v.011l.001.02.003.022.004.021.005.022.006.021.007.022.009.023.01.022.011.023.012.023.013.023.015.023.016.024.017.024.018.023.019.024.021.025.022.024.023.024.024.025.052.05.056.05.061.05.066.051.07.051.075.052.079.051.084.052.088.052.092.052.097.052.102.052.105.051.11.052.114.051.119.051.123.051.127.05.131.05.135.05.139.049.144.048.147.048.152.047.155.046.16.045.163.045.167.043.171.043.176.042.178.04.183.04.187.038.19.037.194.036.197.034.202.033.204.032.209.03.212.028.216.027.219.025.222.024.226.021.23.02.233.018.236.017.24.014.243.012.246.01.249.008.253.006.256.003.259.001.26-.001.257-.003.254-.006.25-.008.247-.01.244-.013.241-.014.237-.016.233-.018.231-.02.226-.022.224-.024.22-.025.216-.027.212-.029.21-.03.205-.032.202-.033.198-.035.194-.036.191-.037.187-.039.183-.039.179-.041.175-.042.172-.043.168-.044.163-.045.16-.045.155-.047.152-.047.148-.048.143-.049.139-.049.136-.049.131-.051.126-.05.123-.051.118-.052.114-.051.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.052.07-.051.065-.051.06-.051.056-.05.051-.049.023-.025.023-.025.021-.024.02-.024.019-.024.018-.024.017-.024.015-.023.014-.024.013-.023.012-.023.01-.022.01-.023.008-.022.006-.022.006-.022.004-.022.004-.021.001-.021.001-.021v-4.153l-.077.054-.08.054-.083.053-.085.053-.087.053-.09.051-.093.051-.095.051-.097.05-.1.049-.102.048-.105.048-.106.048-.109.046-.111.046-.114.046-.115.044-.118.044-.12.043-.122.043-.124.042-.126.041-.128.04-.13.039-.132.039-.134.038-.135.037-.138.036-.139.036-.142.034-.143.034-.144.033-.147.032-.148.032-.15.03-.151.03-.153.028-.154.028-.156.027-.158.026-.159.024-.161.024-.162.023-.163.023-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.01-.178.01-.179.009-.179.007-.181.006-.182.006-.182.004-.184.003-.184.001-.185.001-.185-.001-.184-.001-.184-.003-.182-.004-.182-.006-.181-.006-.179-.007-.179-.009-.178-.01-.176-.01-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.023-.162-.023-.161-.024-.159-.024-.157-.026-.156-.027-.155-.028-.153-.028-.151-.03-.15-.03-.148-.032-.146-.032-.145-.033-.143-.034-.141-.034-.14-.036-.137-.036-.136-.037-.134-.038-.132-.039-.13-.039-.128-.041-.126-.041-.124-.041-.122-.043-.12-.043-.117-.044-.116-.044-.113-.046-.112-.046-.109-.046-.106-.048-.105-.048-.102-.048-.1-.05-.097-.049-.095-.051-.093-.051-.09-.052-.087-.052-.085-.053-.083-.053-.08-.054-.077-.054v4.153zm8.74-8.179l-.257.004-.254.005-.25.008-.247.011-.244.012-.241.014-.237.016-.233.018-.231.021-.226.022-.224.023-.22.026-.216.027-.212.028-.21.031-.205.032-.202.033-.198.034-.194.036-.191.038-.187.038-.183.04-.179.041-.175.042-.172.043-.168.043-.163.045-.16.046-.155.046-.152.048-.148.048-.143.048-.139.049-.136.05-.131.05-.126.051-.123.051-.118.051-.114.052-.11.052-.106.052-.101.052-.096.052-.092.052-.088.052-.083.052-.079.052-.074.051-.07.052-.065.051-.06.05-.056.05-.051.05-.023.025-.023.024-.021.024-.02.025-.019.024-.018.024-.017.023-.015.024-.014.023-.013.023-.012.023-.01.023-.01.022-.008.022-.006.023-.006.021-.004.022-.004.021-.001.021-.001.021.001.021.001.021.004.021.004.022.006.021.006.023.008.022.01.022.01.023.012.023.013.023.014.023.015.024.017.023.018.024.019.024.02.025.021.024.023.024.023.025.051.05.056.05.06.05.065.051.07.052.074.051.079.052.083.052.088.052.092.052.096.052.101.052.106.052.11.052.114.052.118.051.123.051.126.051.131.05.136.05.139.049.143.048.148.048.152.048.155.046.16.046.163.045.168.043.172.043.175.042.179.041.183.04.187.038.191.038.194.036.198.034.202.033.205.032.21.031.212.028.216.027.22.026.224.023.226.022.231.021.233.018.237.016.241.014.244.012.247.011.25.008.254.005.257.004.26.001.26-.001.257-.004.254-.005.25-.008.247-.011.244-.012.241-.014.237-.016.233-.018.231-.021.226-.022.224-.023.22-.026.216-.027.212-.028.21-.031.205-.032.202-.033.198-.034.194-.036.191-.038.187-.038.183-.04.179-.041.175-.042.172-.043.168-.043.163-.045.16-.046.155-.046.152-.048.148-.048.143-.048.139-.049.136-.05.131-.05.126-.051.123-.051.118-.051.114-.052.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.051.07-.052.065-.051.06-.05.056-.05.051-.05.023-.025.023-.024.021-.024.02-.025.019-.024.018-.024.017-.023.015-.024.014-.023.013-.023.012-.023.01-.023.01-.022.008-.022.006-.023.006-.021.004-.022.004-.021.001-.021.001-.021-.001-.021-.001-.021-.004-.021-.004-.022-.006-.021-.006-.023-.008-.022-.01-.022-.01-.023-.012-.023-.013-.023-.014-.023-.015-.024-.017-.023-.018-.024-.019-.024-.02-.025-.021-.024-.023-.024-.023-.025-.051-.05-.056-.05-.06-.05-.065-.051-.07-.052-.074-.051-.079-.052-.083-.052-.088-.052-.092-.052-.096-.052-.101-.052-.106-.052-.11-.052-.114-.052-.118-.051-.123-.051-.126-.051-.131-.05-.136-.05-.139-.049-.143-.048-.148-.048-.152-.048-.155-.046-.16-.046-.163-.045-.168-.043-.172-.043-.175-.042-.179-.041-.183-.04-.187-.038-.191-.038-.194-.036-.198-.034-.202-.033-.205-.032-.21-.031-.212-.028-.216-.027-.22-.026-.224-.023-.226-.022-.231-.021-.233-.018-.237-.016-.241-.014-.244-.012-.247-.011-.25-.008-.254-.005-.257-.004-.26-.001-.26.001z"></path></symbol></defs><defs><symbol id="mermaid-svg-9613216-clock" width="24" height="24"><path transform="scale(.5)" d="M12 2c5.514 0 10 4.486 10 10s-4.486 10-10 10-10-4.486-10-10 4.486-10 10-10zm0-2c-6.627 0-12 5.373-12 12s5.373 12 12 12 12-5.373 12-12-5.373-12-12-12zm5.848 12.459c.202.038.202.333.001.372-1.907.361-6.045 1.111-6.547 1.111-.719 0-1.301-.582-1.301-1.301 0-.512.77-5.447 1.125-7.445.034-.192.312-.181.343.014l.985 6.238 5.394 1.011z"></path></symbol></defs><defs><marker id="mermaid-svg-9613216-arrowhead" refX="7.9" refY="5" markerUnits="userSpaceOnUse" markerWidth="12" markerHeight="12" orient="auto-start-reverse"><path d="M -1 0 L 10 5 L 0 10 z"></path></marker></defs><defs><marker id="mermaid-svg-9613216-crosshead" markerWidth="15" markerHeight="8" orient="auto" refX="4" refY="4.5"><path fill="none" stroke="#000000" stroke-width="1pt" d="M 1,2 L 6,7 M 6,2 L 1,7" style="stroke-dasharray: 0, 0;"></path></marker></defs><defs><marker id="mermaid-svg-9613216-filled-head" refX="15.5" refY="7" markerWidth="20" markerHeight="28" orient="auto"><path d="M 18,7 L9,13 L14,7 L9,1 Z"></path></marker></defs><defs><marker id="mermaid-svg-9613216-sequencenumber" refX="15" refY="15" markerWidth="60" markerHeight="40" orient="auto"><circle cx="15" cy="15" r="6"></circle></marker></defs><defs><marker id="mermaid-svg-9613216-solidTopArrowHead" refX="7.9" refY="7.25" markerUnits="userSpaceOnUse" markerWidth="12" markerHeight="12" orient="auto-start-reverse"><path d="M 0 0 L 10 8 L 0 8 z"></path></marker></defs><defs><marker id="mermaid-svg-9613216-solidBottomArrowHead" refX="7.9" refY="0.75" markerUnits="userSpaceOnUse" markerWidth="12" markerHeight="12" orient="auto-start-reverse"><path d="M 0 0 L 10 0 L 0 8 z"></path></marker></defs><defs><marker id="mermaid-svg-9613216-stickTopArrowHead" refX="7.5" refY="7" markerUnits="userSpaceOnUse" markerWidth="12" markerHeight="12" orient="auto-start-reverse"><path d="M 0 0 L 7 7" stroke="black" stroke-width="1.5" fill="none"></path></marker></defs><defs><marker id="mermaid-svg-9613216-stickBottomArrowHead" refX="7.5" refY="0" markerUnits="userSpaceOnUse" markerWidth="12" markerHeight="12" orient="auto-start-reverse"><path d="M 0 7 L 7 0" stroke="black" stroke-width="1.5" fill="none"></path></marker></defs><g data-et="control-structure" data-id="i13"><line x1="64" y1="231" x2="948" y2="231" stroke="currentColor" stroke-opacity="0.2"></line><line x1="948" y1="231" x2="948" y2="769" stroke="currentColor" stroke-opacity="0.2"></line><line x1="64" y1="769" x2="948" y2="769" stroke="currentColor" stroke-opacity="0.2"></line><line x1="64" y1="231" x2="64" y2="769" stroke="currentColor" stroke-opacity="0.2"></line><line x1="64" y1="520" x2="948" y2="520" style="stroke-dasharray: 3, 3;" stroke="currentColor" stroke-opacity="0.2"></line><polygon points="64,231 114,231 114,244 105.6,251 64,251" fill="none" stroke="currentColor"></polygon><text x="89" y="244" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" style="font-size: 16px; font-weight: 400;" fill="currentColor">alt</text> <text x="531" y="249" text-anchor="middle" style="font-size: 16px; font-weight: 400;" fill="currentColor"><tspan x="531">\[Validation passes]</tspan></text> <text x="506" y="538" text-anchor="middle" style="font-size: 16px; font-weight: 400;" fill="currentColor">\[Validation fails]</text></g> <text x="201" y="80" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" dy="1em" style="font-size: 16px; font-weight: 400;" fill="currentColor">Fills in fields, clicks "Done"</text> <line x1="76" y1="117" x2="326" y2="117" data-et="message" data-id="i0" data-from="Author" data-to="Dialog" stroke-width="2" stroke="none" marker-end="url(#mermaid-svg-9613216-arrowhead)" style="fill: none;"></line><text x="468" y="132" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" dy="1em" style="font-size: 16px; font-weight: 400;" fill="currentColor">Trigger validation for all fields</text> <line x1="331" y1="169" x2="605" y2="169" data-et="message" data-id="i1" data-from="Dialog" data-to="Registry" stroke-width="2" stroke="none" marker-end="url(#mermaid-svg-9613216-arrowhead)" style="fill: none;"></line><text x="772" y="184" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" dy="1em" style="font-size: 16px; font-weight: 400;" fill="currentColor">Run validate() for matching selectors</text> <line x1="610" y1="221" x2="933" y2="221" data-et="message" data-id="i2" data-from="Registry" data-to="Validator" stroke-width="2" stroke="none" marker-end="url(#mermaid-svg-9613216-arrowhead)" style="fill: none;"></line><text x="775" y="282" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" dy="1em" style="font-size: 16px; font-weight: 400;" fill="currentColor">undefined (no error)</text> <line x1="936" y1="319" x2="613" y2="319" data-et="message" data-id="i4" data-from="Validator" data-to="Registry" stroke-width="2" stroke="none" marker-end="url(#mermaid-svg-9613216-arrowhead)" style="stroke-dasharray: 3, 3; fill: none;"></line><text x="471" y="334" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" dy="1em" style="font-size: 16px; font-weight: 400;" fill="currentColor">All valid</text> <line x1="608" y1="371" x2="334" y2="371" data-et="message" data-id="i5" data-from="Registry" data-to="Dialog" stroke-width="2" stroke="none" marker-end="url(#mermaid-svg-9613216-arrowhead)" style="stroke-dasharray: 3, 3; fill: none;"></line><text x="331" y="386" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" dy="1em" style="font-size: 16px; font-weight: 400;" fill="currentColor">Save to JCR</text> <path d="M 331,423 C 391,413 391,453 331,443" data-et="message" data-id="i6" data-from="Dialog" data-to="Dialog" stroke-width="2" stroke="none" marker-end="url(#mermaid-svg-9613216-arrowhead)" style="fill: none;"></path><text x="204" y="468" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" dy="1em" style="font-size: 16px; font-weight: 400;" fill="currentColor">Dialog closes</text> <line x1="329" y1="505" x2="79" y2="505" data-et="message" data-id="i7" data-from="Dialog" data-to="Author" stroke-width="2" stroke="none" marker-end="url(#mermaid-svg-9613216-arrowhead)" style="stroke-dasharray: 3, 3; fill: none;"></line><text x="775" y="566" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" dy="1em" style="font-size: 16px; font-weight: 400;" fill="currentColor">Error message string</text> <line x1="936" y1="603" x2="613" y2="603" data-et="message" data-id="i9" data-from="Validator" data-to="Registry" stroke-width="2" stroke="none" marker-end="url(#mermaid-svg-9613216-arrowhead)" style="stroke-dasharray: 3, 3; fill: none;"></line><text x="772" y="618" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" dy="1em" style="font-size: 16px; font-weight: 400;" fill="currentColor">Run show() to display error</text> <line x1="610" y1="655" x2="933" y2="655" data-et="message" data-id="i10" data-from="Registry" data-to="Validator" stroke-width="2" stroke="none" marker-end="url(#mermaid-svg-9613216-arrowhead)" style="fill: none;"></line><text x="635" y="670" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" dy="1em" style="font-size: 16px; font-weight: 400;" fill="currentColor">Coral Tooltip with error</text> <line x1="936" y1="707" x2="334" y2="707" data-et="message" data-id="i11" data-from="Validator" data-to="Dialog" stroke-width="2" stroke="none" marker-end="url(#mermaid-svg-9613216-arrowhead)" style="stroke-dasharray: 3, 3; fill: none;"></line><text x="204" y="722" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" dy="1em" style="font-size: 16px; font-weight: 400;" fill="currentColor">Error shown, save blocked</text><line x1="329" y1="759" x2="79" y2="759" data-et="message" data-id="i12" data-from="Dialog" data-to="Author" stroke-width="2" stroke="none" marker-end="url(#mermaid-svg-9613216-arrowhead)" style="stroke-dasharray: 3, 3; fill: none;"></line></svg>

The validation framework is based on the **Foundation Validation API**:

1. Validators are registered in the `foundation-registry` with a **CSS selector** that matches target fields
2. When the author submits the dialog, AEM queries all registered validators
3. Each validator's `validate()` function runs against matching fields
4. If `validate()` returns a string (the error message), the save is blocked
5. The `show()` function renders the error tooltip on the invalid field
6. The `clear()` function removes the error when the field becomes valid

### When does validate() fire?

Understanding the trigger points keeps the UX predictable:

| Trigger                                                         | What happens                                                                                                                                      |
| --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| Author clicks **Done** / submits                                | Every registered validator runs against every matching field. First failure blocks the save.                                                      |
| Field adapts to `foundation-field` and calls `.checkValidity()` | Only that field's validators run. Used to trigger validation imperatively from custom JS.                                                         |
| Author leaves a field (blur on most inputs)                     | Coral triggers revalidation on fields that have already been validated once - so the error state clears as soon as the author corrects the value. |
| Author changes a field                                          | Coral re-runs `validate()` if the field is currently marked invalid.                                                                              |

Trigger validation manually on a single field:

```javascript
var $field = $(".my-field");
var api = $field.adaptTo("foundation-field");
if (api && api.checkValidity) {
    var isValid = api.checkValidity(); // also calls show()/clear() as needed
}
```

### Two ways to declare a validator on a field

Either works; mix is fine. The registered validator's selector needs to match both.

```xml
<myField ... validation="my-rule"/>
```

```xml
<myField ...>
    <granite:data
        jcr:primaryType="nt:unstructured"
        foundation-validation="my-rule another-rule"
        max-length="100"/>
</myField>
```

## Setup

### Client Library

Dialog validation code must be loaded in the **authoring context only**. Create a dedicated Client Library:

```xml
<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:cq="http://www.day.com/jcr/cq/1.0"
          xmlns:jcr="http://www.jcp.org/jcr/1.0"
    jcr:primaryType="cq:ClientLibraryFolder"
    allowProxy="{Boolean}true"
    categories="[cq.authoring.dialog]"
    dependencies="[cq.authoring.dialog.all,granite.jquery]"/>
```

| Property                                                  | Purpose                                                   |
| --------------------------------------------------------- | --------------------------------------------------------- |
| `categories="[cq.authoring.dialog]"`                      | Loads the JS only when a Touch UI dialog is open          |
| `dependencies="[cq.authoring.dialog.all,granite.jquery]"` | Ensures the Foundation API and jQuery are available       |
| `allowProxy="{Boolean}true"`                              | Serves the clientlib through the `/etc.clientlibs/` proxy |

### File structure

```markdown
clientlib-dialogvalidation/
├── .content.xml
├── js.txt
└── js/
    ├── urlValidation.js
    ├── extensionValidation.js
    ├── multifieldValidation.js
    ├── charCountValidation.js
    └── conditionalRequiredValidation.js
```

```markdown
#base=js
urlValidation.js
extensionValidation.js
multifieldValidation.js
charCountValidation.js
conditionalRequiredValidation.js
```

## Validator Registration Pattern

Every custom validator follows the same structure:

```javascript
(function ($) {
    "use strict";

    $(window)
        .adaptTo("foundation-registry")
        .register("foundation.validation.validator", {

            // CSS selector that matches the dialog fields to validate.
            // Use ~= so fields with multiple validators still match.
            selector: "[data-validation~='my-custom-rule'], [data-foundation-validation~='my-custom-rule']",

            // Runs when the dialog is submitted or \`checkValidity()\` is called.
            // Return undefined/nothing for valid, or an error message string for invalid.
            validate: function (el) {
                // .val() can return string, number, array (multiselect), or null.
                // Normalise first so downstream logic can assume string.
                var raw = $(el).val();
                var value = (raw == null ? "" : String(raw)).trim();
                if (value.length > 0 && !isValid(value)) {
                    return "Your custom error message here.";
                }
                // Return nothing = valid (empty fields are handled by \`required\` if needed)
            },

            // Renders the error indicator on the field
            show: function (el, message) {
                var $el = $(el);
                var fieldAPI = $el.adaptTo("foundation-field");
                if (fieldAPI && fieldAPI.setInvalid) {
                    fieldAPI.setInvalid(true);
                }

                var error = $el.data("foundation-validation.internal.error");
                if (error) {
                    error.content.innerHTML = message;
                    if (!error.parentNode) {
                        $el.after(error);
                        error.show();
                    }
                } else {
                    error = new Coral.Tooltip();
                    error.variant = "error";
                    error.interaction = "off";
                    error.placement = "bottom";
                    error.target = el;
                    error.content.innerHTML = message;
                    error.open = true;
                    error.id = Coral.commons.getUID();
                    $el.data("foundation-validation.internal.error", error);
                    $el.after(error);
                }
            },

            // Clears the error indicator when the field becomes valid
            clear: function (el) {
                var $el = $(el);
                var fieldAPI = $el.adaptTo("foundation-field");
                if (fieldAPI && fieldAPI.setInvalid) {
                    fieldAPI.setInvalid(false);
                }

                var error = $el.data("foundation-validation.internal.error");
                if (error) {
                    error.hide();
                    error.remove();
                    $el.removeData("foundation-validation.internal.error");
                }
            }
        });
})(Granite.$);
```

### Connecting validators to dialog fields

There are two ways to attach a validator to a dialog field:

**Option 1: `validation` attribute** (simple, single validator)

```xml
<myField
    jcr:primaryType="nt:unstructured"
    sling:resourceType="granite/ui/components/coral/foundation/form/textfield"
    fieldLabel="URL"
    name="./url"
    validation="my-custom-rule"/>
```

**Option 2: `granite:data` node** (multiple validators, custom data attributes)

```xml
<myField
    jcr:primaryType="nt:unstructured"
    sling:resourceType="granite/ui/components/coral/foundation/form/textfield"
    fieldLabel="URL"
    name="./url">
    <granite:data
        jcr:primaryType="nt:unstructured"
        validation="my-custom-rule"
        max-length="100"/>
</myField>
```

:::info Two selectors, two declaration paths A common misconception is that `data-validation` and `data-foundation-validation` are AEMaaCS-vs-6.5. They are not - **both attributes work on both platforms**, and they map to the two different ways you can declare a validator on a field:

| Declaration in the dialog                                    | Attribute that ends up on the rendered HTML |
| ------------------------------------------------------------ | ------------------------------------------- |
| `validation="my-rule"` on the field itself                   | `data-validation="my-rule"`                 |
| `<granite:data foundation-validation="my-rule"/>` child node | `data-foundation-validation="my-rule"`      |

Match both so your validator triggers regardless of how a team member declared it:

```javascript
selector: "[data-validation~='my-rule'], [data-foundation-validation~='my-rule']",
```

Note the `~=` match - Granite concatenates multiple `validation` values with spaces, so exact `=` match can miss fields that have several validators.:::

***

## Validation Examples

### URL Validation (Regex)

Validates that a text field contains a properly formatted URL.

```xml
<endpointUrl
    jcr:primaryType="nt:unstructured"
    sling:resourceType="granite/ui/components/coral/foundation/form/textfield"
    fieldDescription="Please provide a valid URL"
    fieldLabel="External Endpoint (URL)"
    name="./endpointUrl"
    validation="url"
    required="{Boolean}true"/>
```

```javascript
(function ($) {
    "use strict";

    var PATTERN_URL = /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)$/;

    $(window)
        .adaptTo("foundation-registry")
        .register("foundation.validation.validator", {
            selector: "[data-validation~='url'], [data-foundation-validation~='url']",

            validate: function (el) {
                var value = $(el).val().toString().trim();
                if (value.length > 0 && !PATTERN_URL.test(value)) {
                    return "Please enter a valid URL (e.g. https://www.example.com).";
                }
            },

            show: function (el, message) {
                showError($(el), el, message);
            },

            clear: function (el) {
                clearError($(el));
            }
        });

    // Reusable show/clear helpers (shared across validators)
    function showError($el, el, message) {
        var fieldAPI = $el.adaptTo("foundation-field");
        if (fieldAPI && fieldAPI.setInvalid) {
            fieldAPI.setInvalid(true);
        }

        var error = $el.data("foundation-validation.internal.error");
        if (error) {
            error.content.innerHTML = message;
            if (!error.parentNode) {
                $el.after(error);
                error.show();
            }
        } else {
            error = new Coral.Tooltip();
            error.variant = "error";
            error.interaction = "off";
            error.placement = "bottom";
            error.target = el;
            error.content.innerHTML = message;
            error.open = true;
            error.id = Coral.commons.getUID();
            $el.data("foundation-validation.internal.error", error);
            $el.after(error);
        }
    }

    function clearError($el) {
        var fieldAPI = $el.adaptTo("foundation-field");
        if (fieldAPI && fieldAPI.setInvalid) {
            fieldAPI.setInvalid(false);
        }

        var error = $el.data("foundation-validation.internal.error");
        if (error) {
            error.hide();
            error.remove();
            $el.removeData("foundation-validation.internal.error");
        }
    }
})(Granite.$);
```

### File Extension Validation

Restricts a path field to only accept files with specific extensions (e.g. SVG icons only).

```xml
<iconPath
    jcr:primaryType="nt:unstructured"
    sling:resourceType="granite/ui/components/coral/foundation/form/pathfield"
    fieldLabel="Icon Path"
    emptyText="e.g. /content/dam/icons/home.svg"
    filter="hierarchyNotFile"
    name="./iconPath"
    validation="extension-svg"
    rootPath="/content/dam/icons"/>
```

```javascript
(function ($) {
    "use strict";

    var PATTERN_SVG = /^.*\.(svg)$/i;

    $(window)
        .adaptTo("foundation-registry")
        .register("foundation.validation.validator", {
            selector: "[data-validation~='extension-svg'], [data-foundation-validation~='extension-svg']",

            validate: function (el) {
                var value = $(el).val().toString().trim();
                if (value.length > 0 && !PATTERN_SVG.test(value)) {
                    return "Only .svg files are allowed.";
                }
            },

            show: function (el, message) {
                showError($(el), el, message);
            },

            clear: function (el) {
                clearError($(el));
            }
        });

    // ... showError / clearError helpers (same as above) ...
})(Granite.$);
```

:::tip Generic extension validator For a reusable validator that works with any extension, use a `granite:data` attribute to pass the allowed extensions:

```xml
<granite:data
    jcr:primaryType="nt:unstructured"
    validation="file-extension"
    allowed-extensions="jpg,jpeg,png,webp"/>
```

```javascript
validate: function (el) {
    var value = $(el).val().toString().trim();
    var allowed = el.getAttribute("data-allowed-extensions");
    if (value.length > 0 && allowed) {
        var pattern = new RegExp("^.*\\.(" + allowed.replace(/,/g, "|") + ")$", "i");
        if (!pattern.test(value)) {
            return "Allowed file types: " + allowed;
        }
    }
}
```

:::

### Multifield Min / Max Items

Restricts the number of items an author can add to a composite multifield.

```xml
<icons
    jcr:primaryType="nt:unstructured"
    sling:resourceType="granite/ui/components/coral/foundation/form/multifield"
    composite="{Boolean}true">
    <granite:data
        jcr:primaryType="nt:unstructured"
        max-items="5"
        min-items="1"/>
    <field
        jcr:primaryType="nt:unstructured"
        sling:resourceType="granite/ui/components/coral/foundation/container"
        name="./icons">
        <items jcr:primaryType="nt:unstructured">
            <!-- ... fields ... -->
        </items>
    </field>
</icons>
```

```javascript
(function ($) {
    "use strict";

    $(window)
        .adaptTo("foundation-registry")
        .register("foundation.validation.validator", {
            // Match all multifields - the logic checks for data attributes
            selector: "coral-multifield",

            validate: function (el) {
                var totalItems = el.items.getAll().length;
                var min = el.getAttribute("data-min-items");
                var max = el.getAttribute("data-max-items");

                if (min) {
                    min = parseInt(min, 10);
                    if (min > 0 && totalItems < min) {
                        return "Minimum number of items required: " + min
                            + " (currently " + totalItems + ").";
                    }
                }

                if (max) {
                    max = parseInt(max, 10);
                    if (max > 0 && totalItems > max) {
                        return "Maximum number of items allowed: " + max
                            + " (currently " + totalItems + ").";
                    }
                }
            },

            show: function (el, message) {
                // For multifields, attach the error to the multifield element itself
                var $el = $(el);
                var error = $el.data("foundation-validation.internal.error");

                if (error) {
                    error.content.innerHTML = message;
                    if (!error.parentNode) {
                        $el.after(error);
                        error.show();
                    }
                } else {
                    error = new Coral.Tooltip();
                    error.variant = "error";
                    error.interaction = "off";
                    error.placement = "bottom";
                    error.target = el;
                    error.content.innerHTML = message;
                    error.open = true;
                    error.id = Coral.commons.getUID();
                    $el.data("foundation-validation.internal.error", error);
                    $el.after(error);
                }
            },

            clear: function (el) {
                var $el = $(el);
                var error = $el.data("foundation-validation.internal.error");
                if (error) {
                    error.hide();
                    error.remove();
                    $el.removeData("foundation-validation.internal.error");
                }
            }
        });
})(Granite.$);
```

### Character Count / Max Length

Enforces a maximum character count on a text field or textarea, showing the current count.

```xml
<description
    jcr:primaryType="nt:unstructured"
    sling:resourceType="granite/ui/components/coral/foundation/form/textarea"
    fieldLabel="Description"
    fieldDescription="Max 160 characters (SEO meta description)"
    name="./description">
    <granite:data
        jcr:primaryType="nt:unstructured"
        validation="char-count"
        max-chars="160"/>
</description>
```

```javascript
(function ($) {
    "use strict";

    $(window)
        .adaptTo("foundation-registry")
        .register("foundation.validation.validator", {
            selector: "[data-validation~='char-count'], [data-foundation-validation~='char-count']",

            validate: function (el) {
                var value = $(el).val().toString();
                var maxChars = parseInt(el.getAttribute("data-max-chars"), 10);

                if (maxChars && value.length > maxChars) {
                    return "Maximum " + maxChars + " characters allowed ("
                        + value.length + " entered).";
                }
            },

            show: function (el, message) {
                showError($(el), el, message);
            },

            clear: function (el) {
                clearError($(el));
            }
        });

    // ... showError / clearError helpers ...
})(Granite.$);
```

### Email Validation

Validates that a text field contains a properly formatted email address.

```xml
<contactEmail
    jcr:primaryType="nt:unstructured"
    sling:resourceType="granite/ui/components/coral/foundation/form/textfield"
    fieldLabel="Contact Email"
    name="./contactEmail"
    validation="email"/>
```

```javascript
(function ($) {
    "use strict";

    // RFC 5322 simplified pattern
    var PATTERN_EMAIL = /^[a-zA-Z0-9.!#$%&'*+/=?^_\`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;

    $(window)
        .adaptTo("foundation-registry")
        .register("foundation.validation.validator", {
            selector: "[data-validation~='email'], [data-foundation-validation~='email']",

            validate: function (el) {
                var value = $(el).val().toString().trim();
                if (value.length > 0 && !PATTERN_EMAIL.test(value)) {
                    return "Please enter a valid email address.";
                }
            },

            show: function (el, message) {
                showError($(el), el, message);
            },

            clear: function (el) {
                clearError($(el));
            }
        });
})(Granite.$);
```

### Phone Number Validation

Validates international phone number formats.

```xml
<phone
    jcr:primaryType="nt:unstructured"
    sling:resourceType="granite/ui/components/coral/foundation/form/textfield"
    fieldLabel="Phone Number"
    fieldDescription="International format: +49 123 456 7890"
    name="./phone"
    validation="phone"/>
```

```javascript
(function ($) {
    "use strict";

    // Matches international phone formats: +1 234 567 8900, +49-123-456-7890, etc.
    var PATTERN_PHONE = /^\+?[\d\s\-().]{7,20}$/;

    $(window)
        .adaptTo("foundation-registry")
        .register("foundation.validation.validator", {
            selector: "[data-validation~='phone'], [data-foundation-validation~='phone']",

            validate: function (el) {
                var value = $(el).val().toString().trim();
                if (value.length > 0 && !PATTERN_PHONE.test(value)) {
                    return "Please enter a valid phone number (e.g. +49 123 456 7890).";
                }
            },

            show: function (el, message) {
                showError($(el), el, message);
            },

            clear: function (el) {
                clearError($(el));
            }
        });
})(Granite.$);
```

### Conditional Required Field

Makes a field required only when another field has a specific value. For example, "Alt text" is required only when an image is selected.

```xml
<image
    jcr:primaryType="nt:unstructured"
    sling:resourceType="granite/ui/components/coral/foundation/form/pathfield"
    fieldLabel="Image"
    name="./imagePath"
    rootPath="/content/dam"/>

<altText
    jcr:primaryType="nt:unstructured"
    sling:resourceType="granite/ui/components/coral/foundation/form/textfield"
    fieldLabel="Alt Text"
    fieldDescription="Required when an image is selected"
    name="./altText">
    <granite:data
        jcr:primaryType="nt:unstructured"
        validation="conditional-required"
        depends-on="./imagePath"/>
</altText>
```

```javascript
(function ($) {
    "use strict";

    $(window)
        .adaptTo("foundation-registry")
        .register("foundation.validation.validator", {
            selector: "[data-validation~='conditional-required']",

            validate: function (el) {
                var $el = $(el);
                var dependsOnName = el.getAttribute("data-depends-on");
                if (!dependsOnName) return;

                // Find the field this depends on (by its name attribute)
                var $dialog = $el.closest("coral-dialog");
                var $dependsOn = $dialog.find("[name='" + dependsOnName + "']");

                var dependsOnValue = $dependsOn.val();
                var thisValue = $el.val();

                // If the dependency field has a value but this field is empty
                if (dependsOnValue && dependsOnValue.toString().trim().length > 0
                    && (!thisValue || thisValue.toString().trim().length === 0)) {
                    return "This field is required when '"
                        + dependsOnName.replace("./", "") + "' is filled.";
                }
            },

            show: function (el, message) {
                showError($(el), el, message);
            },

            clear: function (el) {
                clearError($(el));
            }
        });
})(Granite.$);
```

### JSON Syntax Validation

Validates that a textarea contains valid JSON (useful for configuration fields).

```xml
<jsonConfig
    jcr:primaryType="nt:unstructured"
    sling:resourceType="granite/ui/components/coral/foundation/form/textarea"
    fieldLabel="JSON Configuration"
    fieldDescription="Must be valid JSON"
    name="./jsonConfig"
    validation="json"/>
```

```javascript
(function ($) {
    "use strict";

    $(window)
        .adaptTo("foundation-registry")
        .register("foundation.validation.validator", {
            selector: "[data-validation~='json'], [data-foundation-validation~='json']",

            validate: function (el) {
                var value = $(el).val().toString().trim();
                if (value.length > 0) {
                    try {
                        JSON.parse(value);
                    } catch (e) {
                        return "Invalid JSON: " + e.message;
                    }
                }
            },

            show: function (el, message) {
                showError($(el), el, message);
            },

            clear: function (el) {
                clearError($(el));
            }
        });
})(Granite.$);
```

### Per-item Multifield Validation

Validating _individual_ items in a composite multifield (e.g. "each link must have both a label and a URL") needs a different selector than the multifield itself. Target the inner input fields and walk up to the enclosing `coral-multifield-item` to reach sibling fields.

```xml
<links
    jcr:primaryType="nt:unstructured"
    sling:resourceType="granite/ui/components/coral/foundation/form/multifield"
    composite="{Boolean}true">
    <field
        jcr:primaryType="nt:unstructured"
        sling:resourceType="granite/ui/components/coral/foundation/container"
        name="./links">
        <items jcr:primaryType="nt:unstructured">
            <label
                jcr:primaryType="nt:unstructured"
                sling:resourceType="granite/ui/components/coral/foundation/form/textfield"
                fieldLabel="Label"
                name="./label">
                <granite:data
                    jcr:primaryType="nt:unstructured"
                    foundation-validation="link-pair"
                    link-role="label"/>
            </label>
            <url
                jcr:primaryType="nt:unstructured"
                sling:resourceType="granite/ui/components/coral/foundation/form/textfield"
                fieldLabel="URL"
                name="./url">
                <granite:data
                    jcr:primaryType="nt:unstructured"
                    foundation-validation="link-pair"
                    link-role="url"/>
            </url>
        </items>
    </field>
</links>
```

```javascript
(function ($) {
    "use strict";

    $(window)
        .adaptTo("foundation-registry")
        .register("foundation.validation.validator", {
            selector: "[data-validation~='link-pair'], [data-foundation-validation~='link-pair']",

            validate: function (el) {
                var $el = $(el);
                // Scope lookups to THIS multifield row - not the whole dialog.
                var $row = $el.closest("coral-multifield-item");
                if ($row.length === 0) return;

                var role = el.getAttribute("data-link-role");
                var value = ($el.val() || "").toString().trim();

                // The other field in the same row
                var otherRole = role === "label" ? "url" : "label";
                var $other = $row.find("[data-link-role='" + otherRole + "']");
                var otherValue = ($other.val() || "").toString().trim();

                // Both empty = OK (author hasn't filled the row yet).
                // Both filled = OK.
                // One filled, one empty = invalid.
                if (value.length === 0 && otherValue.length > 0) {
                    return "Both label and URL are required for each link.";
                }
            },

            show: function (el, message) { showError($(el), el, message); },
            clear: function (el) { clearError($(el)); }
        });
})(Granite.$);
```

:::tip Partner-field revalidation Changing the "URL" input doesn't automatically re-run validation on the "Label" input. After the author edits one side, trigger a `checkValidity()` on the partner so a previously-invalid state clears:

```javascript
$(document).on("change blur", "[data-link-role]", function () {
    var $row = $(this).closest("coral-multifield-item");
    $row.find("[data-link-role]").each(function () {
        var api = $(this).adaptTo("foundation-field");
        if (api && api.checkValidity) api.checkValidity();
    });
});
```

:::

### Async / Server-side Validation

Some rules can only be checked on the server - "is this slug already taken?", "does this product SKU exist?", "is this URL reachable?". The Foundation API is synchronous, so the pattern is: **cache the last server result on the element, debounce fetches, and return synchronously from `validate()`**.

```xml
<slug
    jcr:primaryType="nt:unstructured"
    sling:resourceType="granite/ui/components/coral/foundation/form/textfield"
    fieldLabel="Page Slug"
    fieldDescription="Must be unique across the site"
    name="./slug"
    required="{Boolean}true">
    <granite:data
        jcr:primaryType="nt:unstructured"
        foundation-validation="unique-slug"
        check-url="/bin/myapp/validate/slug"/>
</slug>
```

```javascript
(function ($) {
    "use strict";

    var DEBOUNCE_MS = 350;

    $(window)
        .adaptTo("foundation-registry")
        .register("foundation.validation.validator", {
            selector: "[data-validation~='unique-slug'], [data-foundation-validation~='unique-slug']",

            validate: function (el) {
                var $el = $(el);
                var raw = $el.val();
                var value = (raw == null ? "" : String(raw)).trim();
                if (value.length === 0) return;

                // Cache the last server answer on the DOM element so we can return
                // synchronously. The async fetch (below) re-triggers validation
                // once the response arrives.
                var cached = $el.data("slugValidation");
                if (cached && cached.value === value) {
                    return cached.error; // may be undefined = valid
                }

                scheduleCheck($el, el, value);
                return; // no error yet - optimistic pass; fetch re-validates
            },

            show: function (el, message) { showError($(el), el, message); },
            clear: function (el) { clearError($(el)); }
        });

    function scheduleCheck($el, el, value) {
        var pending = $el.data("slugValidation.timer");
        if (pending) clearTimeout(pending);

        var timer = setTimeout(function () {
            var url = el.getAttribute("data-check-url");
            $.ajax({
                url: url,
                data: { slug: value },
                dataType: "json",
                cache: false
            }).done(function (resp) {
                $el.data("slugValidation", {
                    value: value,
                    error: resp.available ? undefined : "Slug \"" + value + "\" is already in use."
                });
            }).fail(function () {
                // Network / server failure: do NOT block the author from saving.
                $el.data("slugValidation", { value: value, error: undefined });
            }).always(function () {
                // Re-trigger validation so the cached result takes effect.
                var api = $el.adaptTo("foundation-field");
                if (api && api.checkValidity) api.checkValidity();
            });
        }, DEBOUNCE_MS);

        $el.data("slugValidation.timer", timer);
    }
})(Granite.$);
```

:::warning Server-side validation is still required Client-side async checks are a UX optimisation, not a security boundary. The servlet that handles the save (or a `@PostConstruct` hook in the Sling Model) must re-validate uniqueness - a malicious or stale client can submit whatever it wants. See [Server-Side Validation](#server-side-validation) below.:::

***

## Built-in Validation Attributes

AEM provides several built-in validations that don't require custom JavaScript.

### Field-level attributes

Set these directly on the field node:

| Attribute                  | Purpose                    | Applies to              |
| -------------------------- | -------------------------- | ----------------------- |
| `required="{Boolean}true"` | Field must not be empty    | Any field               |
| `max="{Long}100"`          | Maximum numeric value      | `numberfield`           |
| `min="{Long}0"`            | Minimum numeric value      | `numberfield`           |
| `maxlength="{Long}255"`    | Maximum string length      | `textfield`, `textarea` |
| `pattern="^[A-Za-z]+$"`    | HTML5 regex pattern        | `textfield`             |
| `step="{Double}0.01"`      | Numeric step / granularity | `numberfield`           |

### Registered foundation.\* validators

Use these as the value of the `validation` attribute - they are pre-registered by Granite UI:

| Validator key                                | Purpose                                                                         |
| -------------------------------------------- | ------------------------------------------------------------------------------- |
| `foundation.jcr.name`                        | Accepts characters allowed in JCR node names (no `/`, `:`, `[`, `]`, `\|`, `*`) |
| `foundation.jcr.name.path`                   | Same as above, but permits `/` so the value can be a relative path              |
| `foundation.form.field.required`             | Equivalent to `required="{Boolean}true"` declared as a validator                |
| `foundation.form.field.pattern`              | Reads the HTML5 `pattern` attribute and reports a friendlier error              |
| `foundation.form.field.maxlength`            | Reads `maxlength` and enforces it even for pasted content                       |
| `foundation.form.field.step` / `min` / `max` | Number-field bounds and step validation                                         |
| `foundation.validation.number`               | Value must parse as a number (for text-typed inputs)                            |

```xml
<price
    jcr:primaryType="nt:unstructured"
    sling:resourceType="granite/ui/components/coral/foundation/form/numberfield"
    fieldLabel="Price"
    name="./price"
    required="{Boolean}true"
    min="{Double}0.01"
    max="{Double}99999.99"
    step="{Double}0.01"/>

<slug
    jcr:primaryType="nt:unstructured"
    sling:resourceType="granite/ui/components/coral/foundation/form/textfield"
    fieldLabel="Page Slug"
    name="./slug"
    required="{Boolean}true"
    validation="foundation.jcr.name"/>
```

:::note Validator names are not load-bearing The exact `foundation.*` keys shipped by Granite UI are an implementation detail of the platform and occasionally get added to or renamed between versions. If a key above doesn't exist in your release, grep the `granite/ui/components/coral/foundation/clientlibs/foundation/js/validations` folder (or its successor) for the current list.:::

***

## Extracting Reusable Helpers

When you have many validators, extract the `show()` and `clear()` logic into a shared utility to avoid code duplication across files:

```javascript
/**
 * Shared validation error display utilities.
 * Load this file BEFORE the individual validator files (list it first in js.txt).
 */
window.DialogValidation = (function () {
    "use strict";

    function showError($el, el, message) {
        var fieldAPI = $el.adaptTo("foundation-field");
        if (fieldAPI && fieldAPI.setInvalid) {
            fieldAPI.setInvalid(true);
        }

        var error = $el.data("foundation-validation.internal.error");
        if (error) {
            error.content.innerHTML = message;
            if (!error.parentNode) {
                $el.after(error);
                error.show();
            }
        } else {
            error = new Coral.Tooltip();
            error.variant = "error";
            error.interaction = "off";
            error.placement = "bottom";
            error.target = el;
            error.content.innerHTML = message;
            error.open = true;
            error.id = Coral.commons.getUID();
            $el.data("foundation-validation.internal.error", error);
            $el.after(error);
        }
    }

    function clearError($el) {
        var fieldAPI = $el.adaptTo("foundation-field");
        if (fieldAPI && fieldAPI.setInvalid) {
            fieldAPI.setInvalid(false);
        }

        var error = $el.data("foundation-validation.internal.error");
        if (error) {
            error.hide();
            error.remove();
            $el.removeData("foundation-validation.internal.error");
        }
    }

    return {
        showError: showError,
        clearError: clearError
    };
})();
```

Then in each validator file:

```javascript
(function ($) {
    "use strict";

    $(window)
        .adaptTo("foundation-registry")
        .register("foundation.validation.validator", {
            selector: "[data-validation~='email']",
            validate: function (el) {
                // ... validation logic ...
            },
            show: function (el, message) {
                DialogValidation.showError($(el), el, message);
            },
            clear: function (el) {
                DialogValidation.clearError($(el));
            }
        });
})(Granite.$);
```

Updated `js.txt` to load the utility first:

```markdown
#base=js
validationUtils.js
urlValidation.js
extensionValidation.js
emailValidation.js
phoneValidation.js
charCountValidation.js
multifieldValidation.js
conditionalRequiredValidation.js
jsonValidation.js
```

***

## Server-Side Validation

Client-side validation improves the authoring experience, but should **never** be the only layer of defence. Authors can bypass client-side checks (e.g. by editing the JCR directly, using CRXDE, or importing content packages).

For critical business rules, add server-side validation in your Sling Model:

```java
@PostConstruct
protected void init() {
    if (StringUtils.isNotBlank(imagePath) && StringUtils.isBlank(altText)) {
        LOG.warn("Teaser at {} has an image without alt text", resource.getPath());
        // Optionally set a flag for the HTL template to show a warning in edit mode
        hasValidationWarning = true;
    }
}
```

| Layer                         | Purpose                            | Enforcement                      |
| ----------------------------- | ---------------------------------- | -------------------------------- |
| **Client-side (dialog)**      | Immediate feedback, guides authors | Soft - can be bypassed           |
| **Server-side (Sling Model)** | Business rule enforcement          | Hard - always runs               |
| **Content policy**            | Template-level constraints         | Configurable by template authors |

***

## Best Practices and Common Pitfalls

### Always implement clear()

Without a `clear()` function, error tooltips remain visible even after the author corrects the field. This confuses authors and can block saving.

### Match both declaration paths

Include both selector variants so your validator fires regardless of whether the field uses `validation="my-rule"` or `<granite:data foundation-validation="my-rule"/>`:

```javascript
"[data-validation~='my-rule'], [data-foundation-validation~='my-rule']",
```

Use the `~=` space-separated-word selector - Granite renders multiple validators as a space-delimited list, and `=` would miss fields with more than one validator attached.

### Don't block on empty optional fields

If a field is not `required`, your validator should allow empty values. Only validate when the field actually has content:

```javascript
validate: function (el) {
    var value = $(el).val().toString().trim();
    // Only validate non-empty values - empty is OK for optional fields
    if (value.length > 0 && !isValid(value)) {
        return "Error message";
    }
}
```

### Test with multifield items

Validators on fields inside multifields run for every item. Make sure your validator logic handles the DOM structure correctly - the `el` parameter is the specific field instance, not the multifield container.

### Keep error messages helpful

Bad: `"Invalid input"` - Good: `"Please enter a valid URL (e.g. https://www.example.com)"`

Include the expected format, current value count, or a concrete example in the error message.

### Avoid complex cross-field validation

The Foundation Validation API is designed for single-field validation. For complex cross-field rules (e.g. "end date must be after start date"), use the `coral-dialog` submit event instead:

```javascript
$(document).on("click", ".cq-dialog-submit", function (e) {
    var $dialog = $(this).closest("coral-dialog");
    var startDate = $dialog.find("[name='./startDate']").val();
    var endDate = $dialog.find("[name='./endDate']").val();

    if (startDate && endDate && new Date(endDate) <= new Date(startDate)) {
        e.preventDefault();
        e.stopPropagation();
        // Show a Foundation UI notification
        var ui = $(window).adaptTo("foundation-ui");
        ui.alert("Validation Error", "End date must be after start date.", "error");
    }
});
```

## Styling the Invalid State

Calling `fieldAPI.setInvalid(true)` adds the `is-invalid` class to the field element and its surrounding `coral-Form-fieldwrapper`. Coral ships default red styling for these classes, but you can override them in your authoring clientlib if your brand or accessibility review needs stronger affordances.

```markdown
/* Invalid textfield / textarea */
.coral-Form-fieldwrapper.is-invalid > input.coral-Textfield,
.coral-Form-fieldwrapper.is-invalid > textarea.coral-Textfield {
    border-color: #d7373f;
    box-shadow: 0 0 0 1px #d7373f;
}

/* Invalid multifield */
coral-multifield.is-invalid {
    outline: 2px solid #d7373f;
    outline-offset: 2px;
}

/* Tighter spacing for the error tooltip */
coral-tooltip[variant="error"] {
    max-width: 320px;
}
```

Add a `css.txt` next to `js.txt` in the clientlib folder and list `css/validation.css`, then include `css` in the `.content.xml` categories / dependencies as needed. Remember: this CSS only runs inside dialogs, so it can't leak onto published pages.

:::tip Show which validator is failing When debugging dialogs with many overlapping validators, surface the rule name on the wrapper - it survives re-renders and is easy to spot in the inspector:

```javascript
show: function (el, message) {
    $(el).closest("coral-Form-fieldwrapper").attr("data-failed", "my-rule");
    /* ... */
},
clear: function (el) {
    $(el).closest("coral-Form-fieldwrapper").removeAttr("data-failed");
    /* ... */
}
```

:::

## Accessibility

A validation error that is only communicated with a red border is invisible to screen-reader users. Calling `fieldAPI.setInvalid(true)` already does most of the work - Coral sets `aria-invalid="true"` on the control - but make the rest of the experience accessible too:

- **Always show a text message**, never colour alone. The Coral error `Tooltip` you create in `show()` carries the message text; keep it specific (the WCAG "error identification" success criterion).
- **Associate the message with the field.** Give the tooltip an `id` (the examples already use `Coral.commons.getUID()`) and point the field at it with `aria-describedby` so assistive tech reads the error together with the label:

```javascript
show: function (el, message) {
    // ... build the Coral.Tooltip with error.id = Coral.commons.getUID() ...
    el.setAttribute("aria-describedby", error.id);
},
clear: function (el) {
    // ... remove the tooltip ...
    el.removeAttribute("aria-describedby");
}
```

- **Move focus to the first invalid field** on submit so keyboard users land on the problem rather than hunting for it. `checkValidity()` plus `el.focus()` on the first failure is enough.
- **Don't disable the submit button** to "prevent" invalid saves - a disabled control gives no feedback about _why_. Let validation run and report the error instead.

See the [Granite UI `field` accessibility contract](https://developer.adobe.com/experience-manager/reference-materials/6-5/granite-ui/api/jcr_root/libs/granite/ui/components/coral/foundation/form/field/index.html) and the project's [Component Dialogs accessibility notes](https://nhanbe.id.vn/aem/component-dialogs.md#accessibility).

***

## Debugging Validators

Dialogs silently swallowing validation errors is a common frustration. A quick checklist before assuming the framework is broken.

### 1. Confirm the validator is registered

Open the browser devtools on an open dialog and run:

```javascript
// All registered foundation validators
$(window).adaptTo("foundation-registry").get("foundation.validation.validator");
```

If your validator isn't in the list, the clientlib never loaded. Check:

- `categories="[cq.authoring.dialog]"` in the clientlib `.content.xml`
- `allowProxy="{Boolean}true"` (dialogs load via `/etc.clientlibs/`)
- `js.txt` actually lists your JS file
- Proxy cache - hit `/etc.clientlibs/.../clientlib.min.js` directly to confirm the JS is served

### 2. Confirm the selector matches

In the devtools console, with the dialog open:

```javascript
document.querySelectorAll("[data-validation~='my-rule'], [data-foundation-validation~='my-rule']");
```

Zero matches = your field attribute isn't what you think it is. Inspect the rendered HTML - the `validation` property in the dialog XML becomes the `data-validation` attribute on the rendered input, but `granite:data/foundation-validation` becomes `data-foundation-validation`.

### 3. Force a single-field validation

Instead of clicking "Done" and chasing through every validator, trigger only the one you care about:

```javascript
var api = $("[name='./myField']").adaptTo("foundation-field");
api.checkValidity();        // runs validators, triggers show()/clear()
api.isValid();              // reads the current state
```

### 4. Inspect the Coral field API

Multiple validator paths assume `el.adaptTo("foundation-field")` returns a truthy object with `setInvalid` and `checkValidity`. On non-form containers (fieldsets, multifields wrapped in custom components) this can be `null`. Always guard:

```javascript
var api = $(el).adaptTo("foundation-field");
if (api && api.setInvalid) api.setInvalid(true);
```

### 5. Watch the network tab for proxy caching

Edits to dialog clientlib JS sometimes appear to do nothing because the minified bundle is cached. During development, either:

- Append `?debugClientLibs=true` to the page URL to bypass minification, or
- Use the Clientlibs debug page: `/libs/granite/ui/content/dumplibs.html`
