Regle Documentation
website·Indexed 32 days ago
https://reglejs.devA headless validation library for Vue 3.4+, designed to replace repetitive validation logic. Regle features a composable-based API via `useRegle`, support for reusable and built-in rules, async validation, and integration with Nuxt and Standard Schema libraries like Zod and Valibot. It includes specialized tools for handling discriminated unions, scoped validation, and a dedicated Devtools suite for debugging validation trees.
What's inside Regle
- The Regle MCP (Model Context Protocol) server allows AI assistants to interact with Regle's API, providing the assistant with the ability to create form validation rules, search documentation, retrieve precise information on specific rules, create custom rules, and access API information for Regle helpers.
Overview of Regle form validation
Regle is a type-safe, headless form validation library designed to mirror data structures. It provides full TypeScript inference, a model-based validation tree, and a headless architecture that works with any UI framework or CSS library. It is designed as a modern evolution of Vuelidate, featuring an efficient reactivity system and a built-in Vue devtools extension.Access and use Regle rule properties
In Regle, every nested rule status (including the rootr$object) provides a set of computed properties and methods to track the validation state of specific rules. These properties allow developers to programmatically check if a specific rule (likerequired) is valid, pending, or active, and to retrieve its associated error messages or metadata.<script setup lang='ts'> import { useRegle } from '@regle/core'; import { required } from '@regle/rules'; import { ref } from 'vue'; const form = ref({ email: '', user: { firstName: '', lastName: '' } }); const { r$ } = useRegle(form, { email: { required }, user: { firstName: { required }, } }) // Accessing properties of the 'required' rule for the 'email' field console.log(r$.email.$rules.required.$valid); </script>Initialize validation with useRegle
useRegleis the core composable of Regle that transforms form data and validation rules into a reactive validation system. It requires the Vue Composition API to function. It takes three parameters: the state (data), the validation rules, and optional modifiers.<script setup lang='ts'> import { useRegle } from '@regle/core'; const { r$ } = useRegle( /* 1. Your data (state) */, /* 2. Your validation rules */, /* 3. Optional modifiers */ ); // r$ contains validation state, errors, and methods </script>Use Regle MCP server for documentation and autocomplete
Regle provides a Model Context Protocol (MCP) server to provide AI tools (like Cursor or Claude Desktop) with documentation and autocomplete capabilities for Regle.Implement nested variants in Regle
Variants can be nested within the state object. When usingcreateVariantfor nested values, the first argument must be a reactive getter function to ensure Regle can track the nested state changes.const state = ref({ firstName: '', login: { type: '', email: '' } }); const { r$ } = useRegle(state, () => { // Use getter syntax () => state.value.login for nested variants const loginVariant = createVariant(() => state.value.login, 'type', [ { type: { literal: literal('EMAIL') }, email: { required, email } }, { type: { literal: literal('GITHUB') }, username: { required } }, { type: { required } }, ]); return { firstName: { required }, login: loginVariant.value }; });Display validation error messages in templates
Regle is a headless library, meaning you can render error messages using your own UI components. You can access errors for a specific field viar$.field.$errors, or globally viar$.$errors.fieldorr$.$silentErrors.field.<template> <input v-model='r$.$value.email' :class="{ error: r$.email.$error }" placeholder='Type your email' /> <li v-for="error of r$.email.$errors" :key='error'> {{ error }} </li> </template> <script setup lang='ts'> import { useRegle } from '@regle/core'; import { required, minLength, email } from '@regle/rules'; const { r$ } = useRegle({ email: '' }, { email: { required, email, minLength: minLength(4)} }) </script>Handle form submission and validation
Callr$.$validate()to trigger validation for the entire form. This returns an object containing avalidboolean and the validateddata.async function handleSubmit() { const { valid, data } = await r$.$validate() if (!valid) { console.log('Form has errors') return } try { await submitForm(data) r$.$reset() // Reset form after success } catch (error) { // Handle submission error } }Create reusable validation rules with createRule
Use thecreateRuleutility from@regle/coreto define reusable, type-safe validation rules. This utility simplifies the definition of a rule's type, parameters, active state, and automatic tracking of reactive dependencies.import { createRule } from '@regle/core'; import { isFilled } from '@regle/rules'; export const required = createRule({ validator: (value: unknown) => { return isFilled(value); }, message: 'This field is required', });Use schema libraries for form validation
Replace the core
useReglecomposable withuseRegleSchemafrom@regle/schemasto integrate Standard Schema compliant libraries. Regle supports Zod (3.24+), Valibot (1+), and ArkType (2+).Limitations compared to core rules:
- Regle parses the entire tree instead of per-field.
$validateand$pendingare only available at the root level.- Nested values do not have access to properties or methods.
- Access to children
$rules(e.g.,xx.$rules.required.active) is not available.
import { useRegleSchema } from '@regle/schemas'; import { z } from 'zod'; // Or valibot / arktype // Example with Zod const { r$ } = useRegleSchema({ name: '' }, z.object({ name: z.string().min(1) }));Install @regle/rules package
All built-in validation rules are contained in the@regle/rulespackage. This package must be installed separately from the core library.# Using pnpm pnpm add @regle/rules # Using npm npm install @regle/rules # Using yarn yarn add @regle/rules # Using bun bun add @regle/rulesImplement reactive parameters in reusable rules
Regle automatically detects parameters in the
validatorfunction and transforms the rule into a function declaration. These parameters can be plain values, Vue refs, or getter functions, and they are registered as reactive dependencies.Important Reactivity Note: If passing a raw value as a parameter, the rule will only be reactive if the entire rules object is declared as a computed property or a getter function within
useRegle.import { createRule, type Maybe } from '@regle/core'; export const myValidator = createRule({ validator: (value: Maybe<string>, arg: number) => { return true; }, message: ({ $params: [arg] }) => { return `Invalid value based on ${arg}`; } }); // Usage in useRegle const max = ref(5); useRegle({name: ''}, { name: { rule1: myValidator(5), // Plain value rule2: myValidator(max), // Ref rule3: myValidator(() => max.value) // Getter } })