govuk-prototype-kit icon indicating copy to clipboard operation
govuk-prototype-kit copied to clipboard

It's hard to do form validation in the Prototype Kit

Open joelanman opened this issue 2 years ago • 1 comments

This come up on support so just recording the issues around validation in one place.

To validate a form you would check the data in a route. If it's not valid you could redirect back to the original page with, for example ?error=age. You can use that data on the page to show an error summary and error message.

However the auto data store feature means error=age is now stored in session - if a user comes back to this page the error will still show even if they fix it.

Some fixes:

You could remove the data from session manually if the validation checks pass:

delete req.session.data.error

You could use render instead of redirect in your route, which avoids passing the error data from page to page, but rendering on POST means the user sees a nasty warning if they refresh the page or press back to return to it.

You could use the _ naming feature to avoid auto data store(_error=age), but it also means data is not sent to the page, so you'd have to write a route to send it to the page:

res.locals.error = req.query._error

It would be good to have a standardised approach so people don't have to work it out for themselves, and don't use different approaches.

Related

  • #978
  • #509

joelanman avatar Nov 02 '22 14:11 joelanman

https://github.com/alphagov/govuk-prototype-kit-docs/pull/267

oli-rose28 avatar Sep 25 '23 11:09 oli-rose28