CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-vuelidate--validators

Comprehensive validation library for Vue.js applications providing common validators with built-in error messages and customization options

87

1.14x
Overview
Eval results
Files

helpers-utilities.mddocs/

Helper Functions and Utilities

Utility functions for customizing validators with parameters, messages, async behavior, and array validation.

Capabilities

Validator Customization Helpers

Functions available in the helpers namespace for enhancing and customizing validators.

With Parameters Helper

Attaches custom parameters to validators for enhanced error messages and metadata.

/**
 * Attaches custom parameters to a validator
 * @param params - Object containing parameter data
 * @param validator - Validator function to enhance
 * @returns ValidationRuleWithParams containing the validator and parameters
 */
function withParams<T = unknown>(params: object, validator: ValidationRule<T>): ValidationRuleWithParams;

Usage Examples:

import { helpers } from "@vuelidate/validators";

// Add custom parameters to a validator
const customMinLength = helpers.withParams(
  { type: "minLength", min: 5 },
  (value) => value && value.length >= 5
);

// Parameters are available in error messages
const customValidator = helpers.withParams(
  { 
    customParam: "special value",
    threshold: 100,
    validationType: "custom"
  },
  (value) => value > 100
);

// In validation rules
const validationRules = {
  description: {
    customLength: helpers.withParams(
      { min: 10, field: "description" },
      (value) => value && value.length >= 10
    )
  }
};

With Message Helper

Attaches custom error messages to validators.

/**
 * Attaches custom error message to a validator
 * @param message - String message or function that returns message
 * @param validator - Validator function to enhance
 * @returns ValidationRuleWithParams containing the validator and message
 */
function withMessage<T = unknown>(
  message: string | ((params: MessageProps) => string),
  validator: ValidationRule<T>
): ValidationRuleWithParams;

Usage Examples:

import { helpers, required, minLength } from "@vuelidate/validators";

// Static custom message
const customRequired = helpers.withMessage(
  "This field is absolutely required!",
  required
);

// Dynamic message with parameters
const customMinLength = helpers.withMessage(
  (params) => `Minimum length is ${params.$params.min} characters`,
  minLength(5)
);

// Message accessing field data
const contextualMessage = helpers.withMessage(
  (params) => `The ${params.$property} field must be at least ${params.$params.min} characters long`,
  minLength(8)
);

// Complex conditional message
const smartMessage = helpers.withMessage(
  (params) => {
    const value = params.$model;
    const min = params.$params.min;
    const current = value ? value.length : 0;
    return `Field needs ${min - current} more characters (${current}/${min})`;
  },
  minLength(10)
);

// In validation rules
const validationRules = {
  username: {
    required: helpers.withMessage("Username cannot be empty", required),
    minLength: helpers.withMessage(
      "Username must be at least 3 characters long",
      minLength(3)
    )
  }
};

With Async Helper

Marks validators as asynchronous for handling async validation logic.

/**
 * Marks a validator as asynchronous
 * Used for validators that return Promises
 * @param validator - Async validator function
 * @returns Enhanced validator marked as async
 */
const withAsync: Function;

Usage Examples:

import { helpers } from "@vuelidate/validators";

// Async username availability check
const checkUsernameAvailability = helpers.withAsync(async (value) => {
  if (!value) return true; // Let required validator handle empty values
  
  const response = await fetch(`/api/check-username/${value}`);
  const result = await response.json();
  return result.available;
});

// Async email verification
const verifyEmailExists = helpers.withAsync(async (email) => {
  if (!email) return true;
  
  try {
    const response = await fetch('/api/verify-email', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email })
    });
    const result = await response.json();
    return result.exists;
  } catch (error) {
    return false; // Fail validation on network error
  }
});

// Combining async with message
const asyncUsernameValidator = helpers.withMessage(
  "Username is not available",
  helpers.withAsync(checkUsernameAvailability)
);

// In validation rules
const validationRules = {
  username: {
    required,
    minLength: minLength(3),
    available: asyncUsernameValidator
  },
  email: {
    required,
    email,
    verified: helpers.withMessage(
      "Email address could not be verified",
      verifyEmailExists
    )
  }
};

For Each Helper

Applies validators to each element in an array.

/**
 * Applies validators to each element in an array
 * @param validators - Validation rules to apply to array elements
 * @returns Object with $validator and $message for array validation
 */
function forEach(validators: ValidationArgs): { 
  $validator: ValidationRule, 
  $message: () => string 
};

Usage Examples:

import { helpers, required, email, minLength } from "@vuelidate/validators";

// Validate array of emails
const emailListValidation = helpers.forEach({
  required,
  email
});

// Validate array of user objects
const userListValidation = helpers.forEach({
  name: { required, minLength: minLength(2) },
  email: { required, email },
  age: { required, minValue: minValue(18) }
});

// Validate array of strings with multiple rules
const tagListValidation = helpers.forEach({
  required,
  minLength: minLength(2),
  maxLength: maxLength(20),
  alphaNum
});

// In validation rules
const validationRules = {
  emailList: emailListValidation,
  
  userProfiles: userListValidation,
  
  tags: {
    ...tagListValidation,
    // Additional array-level validation
    minItems: (value) => value && value.length >= 1,
    maxItems: (value) => value && value.length <= 10
  }
};

// Example data structure
const formData = {
  emailList: ["user1@example.com", "user2@example.com"],
  userProfiles: [
    { name: "John", email: "john@example.com", age: 25 },
    { name: "Jane", email: "jane@example.com", age: 30 }
  ],
  tags: ["javascript", "vue", "validation"]
};

Core Utility Functions

Low-level utility functions used internally by validators.

Req Function

Core required validation function that checks if a value exists.

/**
 * Core required validation - checks if value exists and is not empty
 * @param value - Value to check
 * @returns true if value exists and is not empty
 */
function req(value: any): boolean;

Len Function

Calculates the length of arrays, objects, or strings.

/**
 * Calculates length of value (array, object, or string)
 * @param value - Value to measure
 * @returns Length as number
 */
function len(value: Array | Object | String): number;

Regex Helper

Creates regex-based validators from regular expression patterns.

/**
 * Creates validator from regular expression patterns
 * @param expr - One or more RegExp patterns
 * @returns Validator function that tests value against patterns
 */
function regex(...expr: RegExp[]): (value: any) => boolean;

Usage Examples:

import { helpers } from "@vuelidate/validators";

// Note: These are typically used internally, but can be used for custom validators

// Custom validator using req
const customRequired = (value) => helpers.req(value);

// Custom length validator using len
const exactLength = (expectedLength) => (value) => {
  return helpers.len(value) === expectedLength;
};

// Custom regex validator
const phonePattern = helpers.regex(/^\(\d{3}\)\s\d{3}-\d{4}$/);
const isValidPhone = phonePattern("(555) 123-4567"); // true

// Multiple regex patterns (must match all)
const strictPattern = helpers.regex(
  /^[a-zA-Z]/, // Must start with letter
  /[0-9]$/,    // Must end with number
  /^.{6,}$/    // Must be at least 6 characters
);

Common Utility Functions

Additional utility functions for working with Vue reactivity and validation responses.

Unwrap Function

Unwraps Vue refs to their actual values (alias for vue-demi's unref).

/**
 * Unwraps Vue ref to actual value
 * @param value - Value that might be a Vue ref
 * @returns Unwrapped value
 */
function unwrap(value: any): any;

Type Checking Utilities

Utility functions for type checking and validation.

/**
 * Checks if value is a function
 * @param val - Value to check
 * @returns true if value is a function
 */
function isFunction(val: any): boolean;

/**
 * Checks if value is an object
 * @param o - Value to check
 * @returns true if value is an object
 */
function isObject(o: any): boolean;

/**
 * Checks if value is truthy
 * @param prop - Value or function to check
 * @returns true if value is truthy
 */
function isTruthy(prop: Function | any): boolean;

/**
 * Checks if value is a Promise
 * @param object - Value to check
 * @returns true if value is a Promise
 */
function isPromise(object: any): boolean;

Advanced Helper Patterns

Combining Multiple Helpers

import { helpers, minLength, required } from "@vuelidate/validators";

// Combine multiple helpers for comprehensive custom validators
const advancedValidator = helpers.withMessage(
  "Field must be provided and meet length requirements",
  helpers.withParams(
    { customType: "advanced", minChars: 5 },
    (value) => helpers.req(value) && helpers.len(value) >= 5
  )
);

// Async validator with custom message and parameters
const asyncCustomValidator = helpers.withMessage(
  (params) => `Validation failed: ${params.$params.reason}`,
  helpers.withParams(
    { reason: "Server validation failed", type: "async" },
    helpers.withAsync(async (value) => {
      // Async validation logic
      return await serverValidation(value);
    })
  )
);

Custom Validator Factory

import { helpers } from "@vuelidate/validators";

// Factory for creating reusable custom validators
function createLengthValidator(min, max, fieldName) {
  return helpers.withMessage(
    `${fieldName} must be between ${min} and ${max} characters`,
    helpers.withParams(
      { min, max, fieldType: fieldName },
      (value) => {
        const length = helpers.len(value);
        return length >= min && length <= max;
      }
    )
  );
}

// Usage
const validationRules = {
  title: createLengthValidator(5, 100, "Title"),
  description: createLengthValidator(10, 500, "Description")
};

Install with Tessl CLI

npx tessl i tessl/npm-vuelidate--validators

docs

conditional-validators.md

core-validators.md

format-validators.md

helpers-utilities.md

index.md

internationalization.md

logical-operators.md

tile.json