Regle Documentation

website·Indexed 29 days ago

https://regle.vercel.app/

A 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, Pinia, and Standard Schema libraries like Zod and Valibot.

Tokens
29K
Snippets
162
Records
195
Agent score
75%

What's inside Regle

  1. Overview of Regle MCP Server capabilities

    The Regle MCP (Model Context Protocol) server allows AI assistants to interact with Regle's API, enabling them to help developers write validation rules more effectively. Key capabilities include creating form validation rules, searching documentation, retrieving precise information on specific rules, creating custom rules, and accessing API information for Regle helpers.
  2. 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.
  3. Use the Regle MCP server for documentation and autocomplete

    Regle provides a Model Context Protocol (MCP) server that allows AI tools to access Regle documentation and provide better autocomplete. It can be configured for use with Cursor and Claude Desktop.
  4. Access and use Regle rule properties

    In Regle, every nested rule status (including the root regle instance) 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 (e.g., required) has passed, is pending, or has a specific error message.
    <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 },
      }
    })
    
    // Access properties for the 'required' rule on the 'email' field
    console.log(r$.email.$rules.required.$valid);
    </script>
  5. Initialize validation with useRegle

    useRegle is the core composable of Regle that bridges form data (state) and validation logic. It requires the Vue Composition API to function. It takes three parameters: the data state, the validation rules, and optional modifiers. It returns an object containing r$, which holds the reactive validation state, errors, and methods.
    <script setup lang='ts'>
    import { useRegle } from '@regle/core';
    
    const { r$ } = useRegle(
      /* 1. Your data (state) */,
      /* 2. Your validation rules */,
      /* 3. Optional modifiers */
    );
    </script>
  6. Install Regle Agent Skills for AI coding agents

    Regle Agent Skills are reusable capabilities that provide AI coding agents with the procedural knowledge required to write Regle validation code effectively. Installing these skills configures the agent to understand core usage, validation rules, advanced patterns, schema integration, TypeScript, and Vuelidate migration.
    npx skills add victorgarciaesgi/regle
  7. Maintain type safety in computed rules using inferRules

    When defining Regle rules in a separate computed property, autocompletion and detailed type checking can be lost. Use the inferRules utility to ensure the rules schema aligns perfectly with the state, preventing mismatched properties and providing better IDE feedback. This requires the state to be declared independently of useRegle.
    import { computed, ref } from 'vue';
    import { inferRules, useRegle } from '@regle/core';
    
    const form = ref({ name: '' });
    
    const rules = computed(() =>
      inferRules(form, {
        name: { /* rules here */ }
      })
    );
    
    const { r$ } = useRegle(form, rules);
  8. Implement scoped validation with useScopedRegle and useCollectScope

    Scoped validation allows a parent component to collect validation states from multiple child or sibling components.

    • useScopedRegle: A version of useRegle that registers its state with a scope. Every time it is called within a Vue instance, it adds an instance for collection.
    • useCollectScope: Retrieves all Regle instances created via useScopedRegle. In the collected state (r$), properties like $value and $errors are converted into arrays instead of objects to accommodate multiple instances.
    <!-- Parent.vue -->
    <script setup lang="ts">
    import { useCollectScope } from '@regle/core';
    const { r$ } = useCollectScope();
    </script>
    <template>
      <Child1 />
      <Child2 />
      Collected errors: <pre>{{ r$.$errors }}</pre>
    </template>
    
    <!-- Child1.vue -->
    <script setup lang="ts">
    import { required } from '@regle/rules';
    import { useScopedRegle } from '@regle/core';
    const { r$ } = useScopedRegle({ firstName: '' }, { firstName: { required } });
    </script>
    <template>
      <input v-model="r$.$value.firstName" />
    </template>
  9. Integrate i18n translations with Regle

    Because Regle is library agnostic, you can pass translation functions (like t from vue-i18n) directly into the withMessage helper.
    <script setup lang='ts'>
    import { useRegle } from '@regle/core';
    import { required, minLength, email, withMessage } from '@regle/rules';
    import { useI18n } from 'vue-i18n';
    
    const { t } = useI18n()
    
    const { r$ } = useRegle({ email: '' }, {
      email: {
        required: withMessage(required, t('general.required')),
        email: withMessage(email, t('general.email')),
        minLength: withMessage(minLength(4), ({$params: [min]}) => t(`general.minLength`, {min}))
      }
    })
    
  10. Create computed schemas with dependencies

    When a schema depends on other state values (e.g., in a refinement or transform), Vue cannot automatically track the dependency inside the function callback. Use the withDeps helper to explicitly force dependencies so the validator re-runs when those values change.
    import { useRegleSchema, inferSchema, withDeps } from '@regle/schemas';
    import { z } from 'zod';
    import { ref, computed } from 'vue';
    
    const form = ref({ firstName: '', lastName: '' });
    
    const schema = computed(() =>
      inferSchema(form, z.object({
        firstName: z.string(),
        lastName: withDeps(
          z.string().refine((v) => v !== form.value.firstName, {
            message: "Last name can't be equal to first name",
          }),
          [() => form.value.firstName] // Force dependency on firstName
        ),
      }))
    );
    
    const { r$ } = useRegleSchema(form, schema);
  11. Migrate validation methods and groups

    The $validate method in Regle returns a destructured object containing valid and data instead of a single result. Validation groups are now defined in the options object using a function that receives the fields.
    // Validation Method
    const { valid, data } = await r$.$validate();
    
    // Validation Groups
    const { r$ } = useRegle(state, {
      number: { isEven },
      nested: { word: { required: v => !!v } }
    }, {
      validationGroups: (fields) => ({
        firstGroup: [fields.number, fields.nested.word]
      })
    });
    
    // Accessing group
    r$.$groups.firstGroup;
  12. Create reusable validation rules with createRule

    Use createRule from @regle/core to define type-safe, reusable validation rules. A rule consists of a validator function that determines if a value is valid and a message function that returns the error string. If the validator returns an object instead of false, that object is passed to the message function, allowing for dynamic, context-aware error messages based on the validator's output.
    import { createRule } from '@regle/core';
    
    export const example = createRule({
      validator: (value) => {
        if (value === 'regle') {
          return {
            $valid: false,
            foo: 'bar'
          }
        }
        return true;
      },
      message({foo}) {
        // 'foo' is available here because it was returned by the validator
        return `Error example: ${foo}`;
      },
    });