Comprehensive validation library for Vue.js applications providing common validators with built-in error messages and customization options
87
Utility functions for customizing validators with parameters, messages, async behavior, and array validation.
Functions available in the helpers namespace for enhancing and customizing validators.
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
)
}
};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)
)
}
};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
)
}
};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"]
};Low-level utility functions used internally by validators.
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;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;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
);Additional utility functions for working with Vue reactivity and validation responses.
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;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;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);
})
)
);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--validatorsdocs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10