Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP - poc(helpers): Generate validation errors #1

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

ttbarnes
Copy link
Owner

@ttbarnes ttbarnes commented Mar 26, 2024

⚠️ WIP

Initial example of a generic helper function 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, with the helper function in place, a service could simply import this and generate validation errors without having to write any specific error messaging logic:

// 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 %}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
1 participant