Skip to Content
ValidationClient-side Validation

Client-side validation for RPC methods

The schema emitted by the server-side code is primarily used to build the RPC modules, but as a side-effect it can also be used for client-side validation. The cllient-side validation library is defined by hooking into the RPC module template via validateOnClient import.

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

vovk-ajv

vovk-ajvΒ  is the primary library that implements the client-side validation using AjvΒ . It is installed and set up automatically when npx vovk-init is used. It validates the JSON schemas emitted by the server-side code. vovk-ajv supports additional configuration listed as config.libs.ajv in the vovk.config file, such as Ajv options, localization and target version of the JSON schema.

npm install vovk-ajv
vovk.config.mjs
/** @type {import('vovk').VovkConfig} */ const config = { 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;

vovk-dto/validateOnClient

When using class-validator for server-side validation, you can use the same DTOs to validate client-side requests. For more information see the DTO client-side validation section.

Custom client-side validation

A custom validateOnClient function can be implemented with createClientValidation function that accepts validate option, that in its turn accepts the input data, validation schema and some extra information about the request. The validate function should return the validated input data or throw an error if the validation fails. The meta object contains information about the request such as type, endpoint, etc. It can optionally throw HttpException with 0 status as default behavior for failed client-side validation.

import { createClientValidation, HttpException, HttpStatus } from 'vovk'; export const validateOnClient = createClientValidation({ 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