Skip to Content
Client-side Validation

Client-Side Validation for RPC Methods

The schema emitted by the server-side code also used for client-side validation. The client-side validation is enabled by wiring a library into the RPC module template via the validateOnClient import.

vovk.config.mjs
/** @type {import('vovk').VovkConfig} */ const config = { outputConfig: { imports: { validateOnClient: 'my-client-validation-library', }, }, }; export default config;

This configuration makes the generated RPC modules import the specified client-side validation library.

./node_modules/.vovk-client/index.mjs
// ...existing code... export const UserRPC = createRPC(schema, '', 'UserRPC', import('vovk'), { validateOnClient: import('my-client-validation-library'), }); // ...existing code...

vovk-ajv

vovk-ajvΒ  is the primary library for client-side validation, built on top of AjvΒ . It’s installed and configured automatically when you run npx vovk-cli init. vovk-ajv supports additional configuration under config.libs.ajv in vovk.config, including Ajv options, localization, and the target JSON Schema draft.

npm install vovk-ajv
vovk.config.mjs
/** @type {import('vovk').VovkConfig} */ const config = { outputConfig: { imports: { validateOnClient: 'vovk-ajv', }, }, libs: { /** @type {import('vovk-ajv').VovkAjvConfig} */ ajv: { options: { // Ajv options strict: false, }, localize: 'en', // language supported by "ajv-i18n" target: 'draft-07', // auto-detected from $schema but can be configured }, }, }; export default config;

Custom Client-Side Validation

You can implement a custom validateOnClient using createValidateOnClient, which accepts a validate option. The validate function receives the input data, the validation schema, and request metadata (meta) such as type, endpoint, and more. It should return validated data, or throw an error on failure. Optionally, throw an HttpException with status 0 (HttpStatus.NULL) to follow the default behavior for failed client-side validation.

import { createValidateOnClient, HttpException, HttpStatus } from 'vovk'; export const validateOnClient = createValidateOnClient({ validate: async (input, schema, meta) => { try { return myValidateFunction(input, schema, meta); } catch (error) { throw new HttpException(HttpStatus.NULL, `Custom validation failed: ${error.message}`); } }, });
Last updated on