Birch UI v0.1
Pricing

Validate form submissions on the serverMIT

Re-check submitted answers on the server with JSON Schema and the expression engine, run async checks while users type, and show the server's errors next to the right fields.

Open .md

Client-side validation helps users fill in a form; it does not protect your data. This recipe validates a service request three times: built-in rules in the browser, a live server check for one field while the user types, and a full check of the submission on the server whose errors are shown next to the fields they belong to.

Steps#

  1. Share one schema module between the browser and the server.
  2. Use a custom validator for checks that need the server while the user types.
  3. On the server, validate the submission with JSON Schema from toJSONSchema(), plus rules that JSON Schema cannot express.
  4. Return errors keyed by field name, and show them in the form with a custom validator and validate().

The shared schema#

shared/service-request.ts
import type { FormSchema } from '@birchui/forms';

export const serviceRequest: FormSchema = {
  title: 'Book a service visit',
  elements: [
    { type: 'text', name: 'contactName', title: 'Your name', required: true },
    { type: 'email', name: 'email', title: 'Email', required: true },
    {
      type: 'text',
      name: 'postcode',
      title: 'Postcode',
      required: true,
      validators: [{ type: 'custom', name: 'inServiceArea' }, { type: 'custom', name: 'server' }],
    },
    { type: 'select', name: 'appliance', title: 'Appliance', required: true, choices: ['Boiler', 'Heat pump', 'EV charger'] },
    { type: 'text', name: 'serialNumber', title: 'Serial number', validators: [{ type: 'custom', name: 'server' }] },
    { type: 'date', name: 'preferredDate', title: 'Preferred date', required: true, validators: [{ type: 'custom', name: 'server' }] },
  ],
};

Every field that the server may reject gets a server custom validator. It shows errors from the last submission; see below.

Live check while typing#

A custom validator can return a promise. Older results are discarded when the user keeps typing, so a slow response never overwrites a newer one:

validators.ts
import type { CustomValidator } from '@birchui/forms';

export const inServiceArea: CustomValidator = async (value) => {
  const response = await fetch(`/api/coverage?postcode=${encodeURIComponent(String(value))}`);
  if (!response.ok) return true;
  const { covered } = (await response.json()) as { covered: boolean };
  return covered ? true : `We do not cover ${String(value)} yet. Call 0161 496 0000 to arrange a visit.`;
};

Returning true when the coverage service is down keeps the form usable; the server checks the postcode again on submit.

Show the server's errors#

The form has no method to set errors from outside, but a custom validator can read them from a map. After a rejected submission, fill the map and call validate():

service-request-form.ts
import { createForm, type CustomValidator } from '@birchui/forms';
import { serviceRequest } from './shared/service-request';
import { inServiceArea } from './validators';

const serverErrors = new Map<string, string>();

const server: CustomValidator = (value, { name }) => {
  const message = serverErrors.get(name);
  return message ?? true;
};

const form = createForm(document.querySelector<HTMLElement>('#service-request')!, {
  schema: serviceRequest,
  customValidators: { inServiceArea, server },
});

form.on('valueChange', ({ name }) => serverErrors.delete(name));

form.on('formSubmit', async ({ data }) => {
  const response = await fetch('/api/service-requests', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data),
  });
  if (response.status === 422) {
    const { errors } = (await response.json()) as { errors: Record<string, string> };
    for (const [name, message] of Object.entries(errors)) serverErrors.set(name, message);
    const { errors: shown } = await form.validate();
    if (shown[0]) form.focusField(shown[0].name);
    return;
  }
  if (!response.ok) {
    showToast('The request could not be sent. Please try again.');
    return;
  }
  showConfirmation();
});

validate() re-runs every rule, so the server's messages appear below their fields and in the error summary. Changing a field removes its server error, and the next check passes.

Validate on the server#

server/service-requests.ts
import Ajv2020 from 'ajv/dist/2020';
import addFormats from 'ajv-formats';
import { toJSONSchema } from '@birchui/forms';
import { serviceRequest } from '../shared/service-request';

const ajv = new Ajv2020({ strict: false, allErrors: true });
addFormats(ajv);
const validateShape = ajv.compile(toJSONSchema(serviceRequest, { extensions: false }));

app.post('/api/service-requests', async (request, response) => {
  const body = request.body as Record<string, unknown>;
  const errors: Record<string, string> = {};

  if (!validateShape(body)) {
    for (const error of validateShape.errors ?? []) {
      const name = error.instancePath.slice(1) || String(error.params.missingProperty ?? 'form');
      errors[name] ??= `This value is not valid: ${error.message}.`;
    }
  }

  if (typeof body.postcode === 'string' && !(await coverage.covers(body.postcode))) {
    errors.postcode = `We do not cover ${body.postcode} yet.`;
  }
  if (typeof body.serialNumber === 'string' && body.serialNumber !== '') {
    const registered = await appliances.findBySerial(body.serialNumber);
    if (!registered) errors.serialNumber = 'We cannot find this serial number. Check the label on the appliance.';
  }
  if (typeof body.preferredDate === 'string' && !(await capacity.hasSlot(body.preferredDate))) {
    errors.preferredDate = 'That day is fully booked. Choose another date.';
  }

  if (Object.keys(errors).length) return response.status(422).json({ errors });
  const id = await serviceRequests.insert(body);
  response.status(201).json({ id });
});

How it works#

  • toJSONSchema() turns the form schema into a JSON Schema that any validator, here Ajv, can check: required fields, types, formats, lengths and choices.
  • Business rules that need data, such as booked capacity, run as ordinary server code and return messages keyed by the field's name.
  • Inside repeating sections, use the field's data path as the key, such as lineItems[1].amount; it is the name the custom validator receives.

Pitfalls#

  • Custom validators run only on fields with a value. A server error for an empty field will not show through the server validator. Mark such fields required so the built-in rule catches them first.
  • requiredIf is not in JSON Schema. Re-check conditional rules with evaluateExpression() on the server.
  • Files. File fields hold File objects in the browser while JSON Schema describes strings; validate uploads separately.
  • Hidden fields. The submitted data leaves out answers of hidden questions by default (clearHiddenValues: 'onSubmit'), so do not require them on the server.

↑ ↓ to move, Enter to open, Esc to close