node.jsjoihapi

Hapi Server Side Validation Results on Frontend with Javascript Disabled


I'm investigating using the Hapi framework on Node.js for building a website where the requirement is for it to work fully with javascript disabled in the browser, and also I can't use HTML 5.

When posting form data, I've had a look at Joi for performing validation on the server side which looks good, but instead of just returning an error code, I need to display this nicely in the front end, eg. red borders around the relevant fields with custom error messages for each field and an error summary.

Is there any way of doing this? Or is there perhaps a plugin that would help without using client side javascript?


Solution

  • Looks like I've found a good way of doing it.

    Simply return the error data in the view along with all the other data that the page binds to by returning h.view on the post method. Then use whatever templating plugin you are using to render the error message or not depending on the data.

    {
      method: 'POST',
      path: currentPath,
      options: {
        validate: {
          options: { abortEarly: false },
          payload: Joi.object({
            isAgent: Joi.string().required()
          }),
          failAction: (request, h, err) => {
            const errorList = []
            const fieldError = findErrorList(err, [isAgent])[0]
            if (fieldError) {
              errorList.push({
                text: fieldError,
                href: `#${field}`
              })
            }
    
            return h.view(viewTemplate, createModel(errorList, request.payload, null)).takeover()
          }
        },
        handler: async (request, h) => {
          return h.redirect(nextPath);
        }
      },
    }