Skip to content
KajayDocs
CustomizeTypeScript SDKextension

Custom validators and expression functions

Add application rules while preserving deterministic validation and expression behavior.

Register custom validators

Subclass Validator for synchronous work or AsyncValidator for a promise. Register the validator as metadata so a JSON definition can name it and the Creator can edit it.

Validator and expression function
import {
  AsyncValidator,
  createDefaultFunctionRegistry,
  globalRegistry,
} from '@kajay/core';

const functions = createDefaultFunctionRegistry();
functions.registerAsync('isserved', async (args) => {
  const postcode = String(args[0] ?? '');
  return checkDeliveryArea(postcode);
});

class ReservedNameValidator extends AsyncValidator {
  override get type(): string { return 'reservednamevalidator'; }
  override async validateAsync({ value }) {
    return (await isReserved(String(value)))
      ? { kind: this.type, text: 'That name is reserved.' }
      : undefined;
  }
}

globalRegistry.addClass({
  name: 'reservednamevalidator',
  parent: 'validator',
  create: () => new ReservedNameValidator(),
});

const { survey } = parseSurvey(definition, { functions });

Use a host-owned function registry

Start from createDefaultFunctionRegistry, register synchronous or asynchronous functions, and pass that registry to parseSurvey. Function names are case-insensitive.

Keep extensions deterministic