Skip to content
PlaygroundForm Builder

You may want to use Valibot validator because:

  • You can use Valibot schema as a source of truth for the form value type (v.InferInput).
  • This is an easy way to add custom error messages
Terminal window
npm i @sjsf/valibot-validator

Required peer dependencies: @sjsf/form@3.5.0 @valibot/to-json-schema@1.3.0 valibot@1.2.0

<script lang="ts">
  import {
    BasicForm,
    createForm,
    getValueSnapshot,
    ON_ARRAY_CHANGE,
    ON_CHANGE,
    ON_INPUT,
  } from "@sjsf/form";
  import { adapt } from "@sjsf/valibot-validator";
  import * as v from "valibot";

  import * as defaults from "$lib/sjsf/defaults";

  import { initialValue, uiSchema } from "../demo-schema";

  const schema = v.object({
    id: v.optional(
      v.pipe(
        v.string(),
        v.regex(new RegExp("^\\d+$"), "Must be a number"),
        v.minLength(8)
      )
    ),
    active: v.optional(v.boolean()),
    skills: v.optional(
      v.pipe(v.array(v.pipe(v.string(), v.minLength(5))), v.minLength(4))
    ),
    multipleChoicesList: v.optional(
      v.pipe(v.array(v.picklist(["foo", "bar", "fuzz"])), v.maxLength(2))
    ),
  });

  const form = createForm({
    ...defaults,
    ...adapt(schema),
    uiSchema,
    fieldsValidationMode: ON_INPUT | ON_CHANGE | ON_ARRAY_CHANGE,
    initialValue,
  });
</script>

<BasicForm {form} novalidate />

<pre>{JSON.stringify(getValueSnapshot(form), null, 2)}</pre>

Types like v.date(), v.bigint(), and v.file() have no JSON Schema equivalent. The adapter converts them to {} (unknown), rendering the default unknown field. You can wire custom field components via UI schema to handle these types. See the example for a working demo.

This validator supports async validation.

import { adaptAsync } from "@sjsf/valibot-validator";
const { schema, validator } = adaptAsync(valibotSchema);