Closed ttbarnes closed 7 months ago
Initial example of a generic helper script that could be used in a NodeJS application to generate a validation error.
The resulting object can then be passed to a nunjucks template and consumed by the Error summary component.
This can be adapted to support mutliple validation errors. This is purely a simple example for a single validation error.
Having this in place would reduce duplication across different services and introduce a structure/patten for other helper functions.
For example:
// my-service/ui/server/controllers/example.js import generateValidationError from '@govuk-frontend/helpers/generate-validation-error'; const REQUIRED_FIELD_ID = 'exampleField'; export const post = (req, res) => { if (!req.body[REQUIRED_FIELD_ID]) { const validationErrors = generateValidationError(REQUIRED_FIELD_ID, 'Field X is required'); if (validationErrors) { return res.render('example.njk', { validationErrors, submittedValues: req.body, }); } } return res.redirect('/next-page'); };
// my-service/ui/server/templates/example.njk {% from 'govuk/components/error-summary/macro.njk' import govukErrorSummary %} {% from 'govuk/components/radios/macro.njk' import govukRadios %} {% block content %} {% if validationErrors.summary %} {{ govukErrorSummary({ titleText: 'There is a problem", errorList: validationErrors.summary }) }} {% endif %} {{ govukRadios({ idPrefix: 'exampleField', name: 'exampleField', errorMessage: validationErrors.errorList.exampleField and { text: validationErrors.errorList.exampleField.text } }) }} {% endmacro %}
⚠️ WIP
Initial example of a generic helper script that could be used in a NodeJS application to generate a validation error.
The resulting object can then be passed to a nunjucks template and consumed by the Error summary component.
This can be adapted to support mutliple validation errors. This is purely a simple example for a single validation error.
Having this in place would reduce duplication across different services and introduce a structure/patten for other helper functions.
For example: