CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-vuelidate--core

Simple, lightweight model-based validation library for Vue.js applications with reactive validation rules and comprehensive error handling.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

index.mddocs/

Vuelidate Core

Vuelidate Core is a simple, lightweight model-based validation library for Vue.js applications. It provides reactive validation rules that integrate seamlessly with Vue's composition API and options API, supporting both Vue 2.x and Vue 3.0.

Package Information

  • Package Name: @vuelidate/core
  • Package Type: npm
  • Language: JavaScript with TypeScript definitions
  • Installation: npm install @vuelidate/core
  • Dependencies: vue-demi (Vue 2/3 compatibility)

Core Imports

import { useVuelidate } from "@vuelidate/core";

For CommonJS:

const { useVuelidate } = require("@vuelidate/core");

Additional exports:

import { useVuelidate, CollectFlag } from "@vuelidate/core";

Basic Usage

Composition API

import { reactive } from "vue";
import { useVuelidate } from "@vuelidate/core";
import { required, email } from "@vuelidate/validators";

export default {
  setup() {
    const state = reactive({
      name: "",
      email: ""
    });
    
    const rules = {
      name: { required },
      email: { required, email }
    };
    
    const v$ = useVuelidate(rules, state);
    
    return { state, v$ };
  }
};

Options API

import { useVuelidate } from "@vuelidate/core";
import { required, email } from "@vuelidate/validators";

export default {
  data() {
    return {
      form: {
        name: "",
        email: ""
      }
    };
  },
  setup: () => ({ v$: useVuelidate() }),
  validations() {
    return {
      form: {
        name: { required },
        email: { required, email }
      }
    };
  }
};

Architecture

Vuelidate Core is built around several key components:

  • Validation Engine: Core validation processing with support for sync and async validators
  • Reactive State Management: Integrates with Vue's reactivity system for real-time validation
  • Nested Validation: Support for validating complex nested object structures
  • Child Component Integration: Collect and aggregate validation state from child components
  • Caching System: Intelligent result caching for performance optimization
  • Configuration System: Global and local configuration options for validation behavior

Capabilities

Core Validation Function

Main composition function for creating validation instances with full TypeScript support and reactive state management.

function useVuelidate(): Ref<Validation>;
function useVuelidate<
  T extends {[key in keyof Vargs]: any},
  Vargs extends ValidationArgs = ValidationArgs,
  EState extends ExtractState<Vargs> = ExtractState<Vargs>
>(
  validationsArgs: Ref<Vargs> | Vargs,
  state: T | Ref<T> | ToRefs<T>,
  globalConfig?: GlobalConfig
): Ref<Validation<Vargs, T>>;

Child Component Collection

Control flags for collecting validation results from child components in parent-child component hierarchies.

enum CollectFlag {
  COLLECT_ALL = true,
  COLLECT_NONE = false
}

Validation Configuration

interface GlobalConfig {
  $registerAs?: string;
  $scope?: string | number | symbol | boolean;
  $stopPropagation?: boolean;
  $autoDirty?: boolean;
  $lazy?: boolean;
  $externalResults?: ServerErrors | Ref<ServerErrors> | UnwrapRef<ServerErrors>;
  $rewardEarly?: boolean;
  currentVueInstance?: ComponentInternalInstance | null;
}

Validation Rules System

type ValidatorFn<T = any, K = any, S = any> = (
  value: T, 
  siblingState: K, 
  vm: S
) => boolean | ValidatorResponse | Promise<boolean | ValidatorResponse>;

interface ValidatorResponse {
  $valid: boolean;
  [key: string]: any;
}

interface ValidationRuleWithoutParams<T = any> {
  $validator: ValidatorFn<T>;
  $message?: string | Ref<string> | (() => string);
}

interface ValidationRuleWithParams<P extends object = object, T = any> {
  $validator: ValidatorFn<T>;
  $message: (input: { $params: P }) => string;
  $params: P;
}

type ValidationRule<T = any> = 
  | ValidationRuleWithParams<any, T> 
  | ValidationRuleWithoutParams<T> 
  | ValidatorFn<T>;

type ValidationRuleCollection<T = any> = Record<string, ValidationRule<T>>;

type ValidationArgs<T = unknown> = {
  [key in keyof T]: ValidationArgs<T[key]> | ValidationRuleCollection<T[key]> | ValidationRule<T[key]>
};

Validation State Interface

interface BaseValidation<
  T = unknown,
  Vrules extends ValidationRuleCollection<T> | undefined = undefined,
> {
  $model: T;
  readonly $dirty: boolean;
  readonly $error: boolean;
  readonly $errors: ErrorObject[];
  readonly $silentErrors: ErrorObject[];
  readonly $externalResults: ErrorObject[];
  readonly $invalid: boolean;
  readonly $anyDirty: boolean;
  readonly $pending: boolean;
  readonly $path: string;
  readonly $touch: () => void;
  readonly $reset: () => void;
  readonly $commit: () => void;
  readonly $validate: () => Promise<boolean>;
  readonly [key: string]: any;
}

type Validation<Vargs extends ValidationArgs = ValidationArgs, T = unknown> =
  NestedValidations<Vargs, T> &
  BaseValidation<T, Vargs extends ValidationRuleCollection ? Vargs : any> &
  ChildValidations;

interface ChildValidations {
  readonly $getResultsForChild: (key: string) => (BaseValidation & ChildValidations) | undefined;
  readonly $clearExternalResults: () => void;
}

Error Handling

interface ErrorObject {
  readonly $propertyPath: string;
  readonly $property: string;
  readonly $validator: string;
  readonly $message: string | Ref<string>;
  readonly $params: object;
  readonly $pending: boolean;
  readonly $response: any;
  readonly $uid: string;
}

interface ServerErrors {
  [key: string]: string | string[] | ServerErrors;
}

Rule Result Types

interface RuleResultWithoutParams {
  readonly $message: string;
  readonly $pending: boolean;
  readonly $invalid: boolean;
  readonly $response: any;
}

interface RuleResultWithParams<P extends object = object> extends RuleResultWithoutParams {
  readonly $params: P;
}

type RuleResult = RuleResultWithoutParams | RuleResultWithParams;

Type Utilities

type ExtractState<Vargs extends ValidationArgs> = 
  Vargs extends ValidationRuleCollection
    ? ExtractStateLeaf<Vargs> & ChildStateLeafs<Vargs>
    : ChildStateLeafs<Vargs>;

type ExtractStateLeaf<Vrules extends ValidationRuleCollection> =
  Vrules extends ValidationRuleCollection<infer T> ? T : unknown;

type ChildStateLeafs<Vargs extends ValidationArgs = ValidationArgs> = {
  [K in keyof Vargs]?: (
    Vargs[K] extends ValidationRuleCollection
      ? ExtractStateLeaf<Vargs[K]>
      : unknown
  ) & (
    Vargs[K] extends Record<string, ValidationArgs>
      ? ChildStateLeafs<Vargs[K]>
      : unknown
  )
};

type NestedValidations<Vargs extends ValidationArgs = ValidationArgs, T = unknown> = {
  readonly [K in keyof Vargs]: BaseValidation<
    T extends Record<K, unknown> ? T[K] : unknown,
    Vargs[K] extends ValidationRuleCollection ? Vargs[K] : undefined
  > & (
    Vargs[K] extends Record<string, ValidationArgs>
      ? NestedValidations<Vargs[K], T extends Record<K, unknown> ? T[K] : unknown>
      : unknown
  )
};

type ToRefs<T> = { [K in keyof T]: Ref<T[K]> };

Advanced Usage Patterns

Lazy Validation

const v$ = useVuelidate(rules, state, { $lazy: true });

Auto-Dirty Mode

const v$ = useVuelidate(rules, state, { $autoDirty: true });

External Server Errors

const serverErrors = ref({});
const v$ = useVuelidate(rules, state, { 
  $externalResults: serverErrors 
});

Child Component Collection

// Parent component
const v$ = useVuelidate({ $scope: 'parentForm' });

// Child component
const childV$ = useVuelidate(childRules, childState, { 
  $scope: 'parentForm',
  $registerAs: 'childComponent'
});

Reward Early Mode

const v$ = useVuelidate(rules, state, { $rewardEarly: true });

Validation Lifecycle

  1. Initialization: Validation rules are processed and watchers are set up
  2. Reactive Updates: State changes trigger validation re-evaluation
  3. Dirty State: Validation errors become active after $touch() or model changes
  4. Async Handling: Async validators set $pending state during execution
  5. Error Collection: Results are aggregated and made available via $errors
  6. Cleanup: Watchers are disposed when components unmount

Common Patterns

Form Validation

// Check if form is ready to submit
if (!v$.$invalid && !v$.$pending) {
  submitForm();
}

// Display errors
v$.$errors.forEach(error => {
  console.log(`${error.$property}: ${error.$message}`);
});

Manual Validation

// Trigger validation manually
const isValid = await v$.$validate();

// Reset validation state
v$.$reset();

Nested Object Validation

const rules = {
  user: {
    name: { required },
    address: {
      street: { required },
      city: { required }
    }
  }
};

// Access nested validation results
console.log(v$.user.name.$error);
console.log(v$.user.address.street.$errors);

docs

index.md

tile.json