CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-vee-validate

Painless forms for Vue.js with comprehensive validation, composition API, and component-based approaches.

Pending
Overview
Eval results
Files

core-validation.mddocs/

Core Validation

Core validation functions for validating individual values and objects against rules or schemas without requiring Vue context. These functions can be used independently in any JavaScript/TypeScript environment.

Capabilities

validate Function

Validates a single value against provided validation rules.

/**
 * Validates a single value against provided validation rules
 * @param value - The value to validate
 * @param rules - Validation rules (string, object, function, array of functions, or TypedSchema)
 * @param options - Optional validation configuration
 * @returns Promise resolving to validation result
 */
function validate<TInput, TOutput = TInput>(
  value: TInput,
  rules: string | Record<string, unknown> | GenericValidateFunction<TInput> | GenericValidateFunction<TInput>[] | TypedSchema<TInput, TOutput>,
  options?: ValidationOptions
): Promise<ValidationResult<TOutput>>;

interface ValidationOptions {
  name?: string;
  label?: string;
  values?: Record<string, unknown>;
  bails?: boolean;
}

interface ValidationResult<TValue = unknown> {
  errors: string[];
  valid: boolean;
  value?: TValue;
}

Usage Examples:

import { validate } from "vee-validate";

// String rule validation
const result1 = await validate("", "required");
// Result: { valid: false, errors: ["This field is required"] }

// Function rule validation
const result2 = await validate("test@example.com", (value) => {
  if (!value) return "Email is required";
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) return "Email is invalid";
  return true;
});
// Result: { valid: true, errors: [] }

// Multiple rules validation
const result3 = await validate("ab", [
  (value) => value.length >= 3 || "Too short",
  (value) => /^[a-zA-Z]+$/.test(value) || "Letters only"
]);
// Result: { valid: false, errors: ["Too short"] }

// With options
const result4 = await validate("", "required", {
  name: "email",
  label: "Email Address"
});
// Result: { valid: false, errors: ["Email Address is required"] }

validateObject Function

Validates an entire object against a schema of field validation rules.

/**
 * Validates an object against a schema of field validation rules
 * @param schema - Object mapping field paths to validation rules
 * @param values - Object to validate
 * @param options - Optional configuration for field names and bails behavior
 * @returns Promise resolving to form validation result
 */
function validateObject<TValues extends GenericObject, TOutput extends GenericObject = TValues>(
  schema: RawFormSchema<TValues>,
  values: TValues,
  options?: {
    names?: Record<string, string>;
    bailsMap?: Record<string, boolean>;
  }
): Promise<FormValidationResult<TValues, TOutput>>;

type RawFormSchema<TValues> = Record<Path<TValues>, string | GenericValidateFunction | GenericObject>;

interface FormValidationResult<TInput extends GenericObject, TOutput extends GenericObject = TInput> {
  valid: boolean;
  results: Partial<FlattenAndMapPathsValidationResult<TInput, TOutput>>;
  errors: Partial<Record<Path<TInput>, string>>;
  values?: Partial<TOutput>;
  source: 'schema' | 'fields' | 'none';
}

Usage Examples:

import { validateObject } from "vee-validate";

// Object validation with function rules
const userSchema = {
  name: (value) => value ? true : "Name is required",
  email: (value) => {
    if (!value) return "Email is required";
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) return "Email is invalid";
    return true;
  },
  age: (value) => {
    if (!value) return "Age is required";
    if (value < 18) return "Must be at least 18";
    return true;
  }
};

const userData = {
  name: "John Doe",
  email: "invalid-email",
  age: 16
};

const result = await validateObject(userSchema, userData);
/*
Result: {
  valid: false,
  errors: {
    email: "Email is invalid",
    age: "Must be at least 18"
  },
  results: {
    name: { valid: true, errors: [] },
    email: { valid: false, errors: ["Email is invalid"] },
    age: { valid: false, errors: ["Must be at least 18"] }
  },
  source: "fields"
}
*/

// With custom field names
const resultWithNames = await validateObject(userSchema, userData, {
  names: {
    name: "Full Name",
    email: "Email Address",
    age: "Age"
  }
});

// Nested object validation
const nestedSchema = {
  "user.name": (value) => value ? true : "User name is required",
  "user.profile.bio": (value) => value.length <= 500 || "Bio too long"
};

const nestedData = {
  user: {
    name: "",
    profile: { bio: "A very long bio..." }
  }
};

const nestedResult = await validateObject(nestedSchema, nestedData);

Validation Rule Types

String Rules

String-based validation rules that reference globally defined rules.

// String rule format: "ruleName" or "ruleName:param1,param2"
type StringRule = string;

Function Rules

Custom validation functions for specific validation logic.

/**
 * Generic validation function that returns true for valid, or error message(s) for invalid
 */
type GenericValidateFunction<TValue = unknown> = (
  value: TValue,
  ctx: FieldValidationMetaInfo
) => MaybePromise<boolean | MaybeArray<string>>;

interface FieldValidationMetaInfo {
  field: string;
  name: string;
  label?: string;
  form: Record<string, unknown>;
  rule?: {
    name: string;
    params?: Record<string, unknown> | unknown[];
  };
}

Object Rules

Rules defined as objects with parameters for built-in validators.

// Object rule format for parameterized validation
type ObjectRule = Record<string, unknown>;

// Example: { required: true, min: 3, max: 50 }

Schema Rules

TypedSchema interface for integration with validation libraries like Yup, Zod, Joi.

interface TypedSchema<TInput = any, TOutput = TInput> {
  __type: 'VVTypedSchema';
  parse(values: TInput, context?: TypedSchemaContext): Promise<{ value?: TOutput; errors: TypedSchemaError[] }>;
  cast?(values: Partial<TInput>): TInput;
  describe?(path?: Path<TInput>): Partial<TypedSchemaPathDescription>;
}

interface TypedSchemaContext {
  formData: GenericObject;
}

interface TypedSchemaError {
  path?: string;
  errors: string[];
}

interface TypedSchemaPathDescription {
  required: boolean;
  exists: boolean;
}

Error Handling

All validation functions handle errors gracefully and provide structured error information:

// Validation errors are always returned as arrays of strings
type ValidationErrors = string[];

// Form validation provides detailed error mapping
type FormErrors<TValues extends GenericObject> = Partial<Record<Path<TValues> | '', string | undefined>>;
type FormErrorBag<TValues extends GenericObject> = Partial<Record<Path<TValues> | '', string[]>>;

Error Handling Examples:

import { validate, validateObject } from "vee-validate";

// Single field error handling
try {
  const result = await validate("", "required");
  if (!result.valid) {
    console.log("Validation errors:", result.errors);
    // Handle validation errors
  }
} catch (error) {
  console.log("Validation failed:", error);
  // Handle unexpected errors
}

// Object validation error handling
try {
  const result = await validateObject(schema, data);
  if (!result.valid) {
    Object.entries(result.errors).forEach(([field, error]) => {
      console.log(`${field}: ${error}`);
    });
  }
} catch (error) {
  console.log("Schema validation failed:", error);
}

Install with Tessl CLI

npx tessl i tessl/npm-vee-validate

docs

configuration-rules.md

core-validation.md

field-management.md

form-actions.md

form-management.md

index.md

state-access.md

vue-components.md

tile.json