Skip to content
Playground

Ajv

Form validator implementation based on Ajv@8 JSON schema validator.

Installation

Terminal window
npm i @sjsf/ajv8-validator ajv@8

Example

<script lang="ts">
import { ON_INPUT, RawForm } from "@sjsf/form";
import { createValidator2 } from "@sjsf/ajv8-validator";
import { createCustomForm } from "@/components/custom-form";
import { schema, uiSchema } from "./_shared";
const validator = createValidator2({
uiSchema,
});
const form = createCustomForm({
schema,
uiSchema,
validator,
fieldsValidationMode: ON_INPUT,
initialValue: {
id: "Invalid",
skills: ["karate", "budo", "aikido"],
multipleChoicesList: ["foo", "bar", "fuzz"],
},
});
</script>
<RawForm {form} novalidate />
<pre>{JSON.stringify(form.value, null, 2)}</pre>

Async validation

This validator supports async validation.

Asynchronous validation

import { createAsyncValidator } from "@sjsf/ajv8-validator";
const validator = createAsyncValidator({
ajv: yourAjvInstance,
})

API

import type { Options, Ajv, ValidateFunction, AsyncValidateFunction } from "ajv";
import type { UiSchemaRoot, Schema, Config } from '@sjsf/form'
import type { AsyncValidator, Validator } from '@sjsf/ajv8-validator'
interface AbstractValidatorOptions {
ajv: Ajv;
/**
* Necessary for correct inference of the field title
* @default {}
*/
uiSchema?: UiSchemaRoot;
/** @default DEFAULT_ID_PREFIX */
idPrefix?: string;
/** @default DEFAULT_ID_SEPARATOR */
idSeparator?: string;
/** @default DEFAULT_PSEUDO_ID_SEPARATOR */
idPseudoSeparator?: string;
}
interface ValidatorOptions extends AbstractValidatorOptions {
/** @default makeSchemaCompiler(ajv, false) */
compileSchema?: (schema: Schema, rootSchema: Schema) => ValidateFunction;
/** @default makeFieldSchemaCompiler(ajv, false) */
compileFieldSchema?: (config: Config) => ValidateFunction;
}
type FactoryOptions<O> = Omit<O, "ajv"> & {
/** @default DEFAULT_AJV_CONFIG */
ajvOptions?: Options;
/** @default addFormComponents(new Ajv(ajvOptions)) */
ajv?: Ajv;
};
function createValidator2(options?: FactoryOptions<ValidatorOptions>): Validator
interface AsyncValidatorOptions extends AbstractValidatorOptions {
/** @default makeSchemaCompiler(ajv, false) */
compileSchema?: (schema: Schema, rootSchema: Schema) => ValidateFunction;
/** @default makeSchemaCompiler(ajv, true) */
compileAsyncSchema?: (
schema: Schema,
rootSchema: Schema
) => AsyncValidateFunction;
/** @default makeFieldSchemaCompiler(ajv, true) */
compileAsyncFieldSchema?: (config: Config) => AsyncValidateFunction;
}
function createAsyncValidator(options?: FactoryOptions<AsyncValidatorOptions>): AsyncValidator