0
# Helper Functions and Utilities
1
2
Utility functions for customizing validators with parameters, messages, async behavior, and array validation.
3
4
## Capabilities
5
6
### Validator Customization Helpers
7
8
Functions available in the `helpers` namespace for enhancing and customizing validators.
9
10
#### With Parameters Helper
11
12
Attaches custom parameters to validators for enhanced error messages and metadata.
13
14
```javascript { .api }
15
/**
16
* Attaches custom parameters to a validator
17
* @param params - Object containing parameter data
18
* @param validator - Validator function to enhance
19
* @returns ValidationRuleWithParams containing the validator and parameters
20
*/
21
function withParams<T = unknown>(params: object, validator: ValidationRule<T>): ValidationRuleWithParams;
22
```
23
24
**Usage Examples:**
25
26
```javascript
27
import { helpers } from "@vuelidate/validators";
28
29
// Add custom parameters to a validator
30
const customMinLength = helpers.withParams(
31
{ type: "minLength", min: 5 },
32
(value) => value && value.length >= 5
33
);
34
35
// Parameters are available in error messages
36
const customValidator = helpers.withParams(
37
{
38
customParam: "special value",
39
threshold: 100,
40
validationType: "custom"
41
},
42
(value) => value > 100
43
);
44
45
// In validation rules
46
const validationRules = {
47
description: {
48
customLength: helpers.withParams(
49
{ min: 10, field: "description" },
50
(value) => value && value.length >= 10
51
)
52
}
53
};
54
```
55
56
#### With Message Helper
57
58
Attaches custom error messages to validators.
59
60
```javascript { .api }
61
/**
62
* Attaches custom error message to a validator
63
* @param message - String message or function that returns message
64
* @param validator - Validator function to enhance
65
* @returns ValidationRuleWithParams containing the validator and message
66
*/
67
function withMessage<T = unknown>(
68
message: string | ((params: MessageProps) => string),
69
validator: ValidationRule<T>
70
): ValidationRuleWithParams;
71
```
72
73
**Usage Examples:**
74
75
```javascript
76
import { helpers, required, minLength } from "@vuelidate/validators";
77
78
// Static custom message
79
const customRequired = helpers.withMessage(
80
"This field is absolutely required!",
81
required
82
);
83
84
// Dynamic message with parameters
85
const customMinLength = helpers.withMessage(
86
(params) => `Minimum length is ${params.$params.min} characters`,
87
minLength(5)
88
);
89
90
// Message accessing field data
91
const contextualMessage = helpers.withMessage(
92
(params) => `The ${params.$property} field must be at least ${params.$params.min} characters long`,
93
minLength(8)
94
);
95
96
// Complex conditional message
97
const smartMessage = helpers.withMessage(
98
(params) => {
99
const value = params.$model;
100
const min = params.$params.min;
101
const current = value ? value.length : 0;
102
return `Field needs ${min - current} more characters (${current}/${min})`;
103
},
104
minLength(10)
105
);
106
107
// In validation rules
108
const validationRules = {
109
username: {
110
required: helpers.withMessage("Username cannot be empty", required),
111
minLength: helpers.withMessage(
112
"Username must be at least 3 characters long",
113
minLength(3)
114
)
115
}
116
};
117
```
118
119
#### With Async Helper
120
121
Marks validators as asynchronous for handling async validation logic.
122
123
```javascript { .api }
124
/**
125
* Marks a validator as asynchronous
126
* Used for validators that return Promises
127
* @param validator - Async validator function
128
* @returns Enhanced validator marked as async
129
*/
130
const withAsync: Function;
131
```
132
133
**Usage Examples:**
134
135
```javascript
136
import { helpers } from "@vuelidate/validators";
137
138
// Async username availability check
139
const checkUsernameAvailability = helpers.withAsync(async (value) => {
140
if (!value) return true; // Let required validator handle empty values
141
142
const response = await fetch(`/api/check-username/${value}`);
143
const result = await response.json();
144
return result.available;
145
});
146
147
// Async email verification
148
const verifyEmailExists = helpers.withAsync(async (email) => {
149
if (!email) return true;
150
151
try {
152
const response = await fetch('/api/verify-email', {
153
method: 'POST',
154
headers: { 'Content-Type': 'application/json' },
155
body: JSON.stringify({ email })
156
});
157
const result = await response.json();
158
return result.exists;
159
} catch (error) {
160
return false; // Fail validation on network error
161
}
162
});
163
164
// Combining async with message
165
const asyncUsernameValidator = helpers.withMessage(
166
"Username is not available",
167
helpers.withAsync(checkUsernameAvailability)
168
);
169
170
// In validation rules
171
const validationRules = {
172
username: {
173
required,
174
minLength: minLength(3),
175
available: asyncUsernameValidator
176
},
177
email: {
178
required,
179
email,
180
verified: helpers.withMessage(
181
"Email address could not be verified",
182
verifyEmailExists
183
)
184
}
185
};
186
```
187
188
#### For Each Helper
189
190
Applies validators to each element in an array.
191
192
```javascript { .api }
193
/**
194
* Applies validators to each element in an array
195
* @param validators - Validation rules to apply to array elements
196
* @returns Object with $validator and $message for array validation
197
*/
198
function forEach(validators: ValidationArgs): {
199
$validator: ValidationRule,
200
$message: () => string
201
};
202
```
203
204
**Usage Examples:**
205
206
```javascript
207
import { helpers, required, email, minLength } from "@vuelidate/validators";
208
209
// Validate array of emails
210
const emailListValidation = helpers.forEach({
211
required,
212
213
});
214
215
// Validate array of user objects
216
const userListValidation = helpers.forEach({
217
name: { required, minLength: minLength(2) },
218
email: { required, email },
219
age: { required, minValue: minValue(18) }
220
});
221
222
// Validate array of strings with multiple rules
223
const tagListValidation = helpers.forEach({
224
required,
225
minLength: minLength(2),
226
maxLength: maxLength(20),
227
alphaNum
228
});
229
230
// In validation rules
231
const validationRules = {
232
emailList: emailListValidation,
233
234
userProfiles: userListValidation,
235
236
tags: {
237
...tagListValidation,
238
// Additional array-level validation
239
minItems: (value) => value && value.length >= 1,
240
maxItems: (value) => value && value.length <= 10
241
}
242
};
243
244
// Example data structure
245
const formData = {
246
emailList: ["user1@example.com", "user2@example.com"],
247
userProfiles: [
248
{ name: "John", email: "john@example.com", age: 25 },
249
{ name: "Jane", email: "jane@example.com", age: 30 }
250
],
251
tags: ["javascript", "vue", "validation"]
252
};
253
```
254
255
### Core Utility Functions
256
257
Low-level utility functions used internally by validators.
258
259
#### Req Function
260
261
Core required validation function that checks if a value exists.
262
263
```javascript { .api }
264
/**
265
* Core required validation - checks if value exists and is not empty
266
* @param value - Value to check
267
* @returns true if value exists and is not empty
268
*/
269
function req(value: any): boolean;
270
```
271
272
#### Len Function
273
274
Calculates the length of arrays, objects, or strings.
275
276
```javascript { .api }
277
/**
278
* Calculates length of value (array, object, or string)
279
* @param value - Value to measure
280
* @returns Length as number
281
*/
282
function len(value: Array | Object | String): number;
283
```
284
285
#### Regex Helper
286
287
Creates regex-based validators from regular expression patterns.
288
289
```javascript { .api }
290
/**
291
* Creates validator from regular expression patterns
292
* @param expr - One or more RegExp patterns
293
* @returns Validator function that tests value against patterns
294
*/
295
function regex(...expr: RegExp[]): (value: any) => boolean;
296
```
297
298
**Usage Examples:**
299
300
```javascript
301
import { helpers } from "@vuelidate/validators";
302
303
// Note: These are typically used internally, but can be used for custom validators
304
305
// Custom validator using req
306
const customRequired = (value) => helpers.req(value);
307
308
// Custom length validator using len
309
const exactLength = (expectedLength) => (value) => {
310
return helpers.len(value) === expectedLength;
311
};
312
313
// Custom regex validator
314
const phonePattern = helpers.regex(/^\(\d{3}\)\s\d{3}-\d{4}$/);
315
const isValidPhone = phonePattern("(555) 123-4567"); // true
316
317
// Multiple regex patterns (must match all)
318
const strictPattern = helpers.regex(
319
/^[a-zA-Z]/, // Must start with letter
320
/[0-9]$/, // Must end with number
321
/^.{6,}$/ // Must be at least 6 characters
322
);
323
```
324
325
### Common Utility Functions
326
327
Additional utility functions for working with Vue reactivity and validation responses.
328
329
#### Unwrap Function
330
331
Unwraps Vue refs to their actual values (alias for vue-demi's unref).
332
333
```javascript { .api }
334
/**
335
* Unwraps Vue ref to actual value
336
* @param value - Value that might be a Vue ref
337
* @returns Unwrapped value
338
*/
339
function unwrap(value: any): any;
340
```
341
342
#### Type Checking Utilities
343
344
Utility functions for type checking and validation.
345
346
```javascript { .api }
347
/**
348
* Checks if value is a function
349
* @param val - Value to check
350
* @returns true if value is a function
351
*/
352
function isFunction(val: any): boolean;
353
354
/**
355
* Checks if value is an object
356
* @param o - Value to check
357
* @returns true if value is an object
358
*/
359
function isObject(o: any): boolean;
360
361
/**
362
* Checks if value is truthy
363
* @param prop - Value or function to check
364
* @returns true if value is truthy
365
*/
366
function isTruthy(prop: Function | any): boolean;
367
368
/**
369
* Checks if value is a Promise
370
* @param object - Value to check
371
* @returns true if value is a Promise
372
*/
373
function isPromise(object: any): boolean;
374
```
375
376
## Advanced Helper Patterns
377
378
### Combining Multiple Helpers
379
380
```javascript
381
import { helpers, minLength, required } from "@vuelidate/validators";
382
383
// Combine multiple helpers for comprehensive custom validators
384
const advancedValidator = helpers.withMessage(
385
"Field must be provided and meet length requirements",
386
helpers.withParams(
387
{ customType: "advanced", minChars: 5 },
388
(value) => helpers.req(value) && helpers.len(value) >= 5
389
)
390
);
391
392
// Async validator with custom message and parameters
393
const asyncCustomValidator = helpers.withMessage(
394
(params) => `Validation failed: ${params.$params.reason}`,
395
helpers.withParams(
396
{ reason: "Server validation failed", type: "async" },
397
helpers.withAsync(async (value) => {
398
// Async validation logic
399
return await serverValidation(value);
400
})
401
)
402
);
403
```
404
405
### Custom Validator Factory
406
407
```javascript
408
import { helpers } from "@vuelidate/validators";
409
410
// Factory for creating reusable custom validators
411
function createLengthValidator(min, max, fieldName) {
412
return helpers.withMessage(
413
`${fieldName} must be between ${min} and ${max} characters`,
414
helpers.withParams(
415
{ min, max, fieldType: fieldName },
416
(value) => {
417
const length = helpers.len(value);
418
return length >= min && length <= max;
419
}
420
)
421
);
422
}
423
424
// Usage
425
const validationRules = {
426
title: createLengthValidator(5, 100, "Title"),
427
description: createLengthValidator(10, 500, "Description")
428
};
429
```