0
# Core Validation
1
2
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.
3
4
## Capabilities
5
6
### validate Function
7
8
Validates a single value against provided validation rules.
9
10
```typescript { .api }
11
/**
12
* Validates a single value against provided validation rules
13
* @param value - The value to validate
14
* @param rules - Validation rules (string, object, function, array of functions, or TypedSchema)
15
* @param options - Optional validation configuration
16
* @returns Promise resolving to validation result
17
*/
18
function validate<TInput, TOutput = TInput>(
19
value: TInput,
20
rules: string | Record<string, unknown> | GenericValidateFunction<TInput> | GenericValidateFunction<TInput>[] | TypedSchema<TInput, TOutput>,
21
options?: ValidationOptions
22
): Promise<ValidationResult<TOutput>>;
23
24
interface ValidationOptions {
25
name?: string;
26
label?: string;
27
values?: Record<string, unknown>;
28
bails?: boolean;
29
}
30
31
interface ValidationResult<TValue = unknown> {
32
errors: string[];
33
valid: boolean;
34
value?: TValue;
35
}
36
```
37
38
**Usage Examples:**
39
40
```typescript
41
import { validate } from "vee-validate";
42
43
// String rule validation
44
const result1 = await validate("", "required");
45
// Result: { valid: false, errors: ["This field is required"] }
46
47
// Function rule validation
48
const result2 = await validate("test@example.com", (value) => {
49
if (!value) return "Email is required";
50
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) return "Email is invalid";
51
return true;
52
});
53
// Result: { valid: true, errors: [] }
54
55
// Multiple rules validation
56
const result3 = await validate("ab", [
57
(value) => value.length >= 3 || "Too short",
58
(value) => /^[a-zA-Z]+$/.test(value) || "Letters only"
59
]);
60
// Result: { valid: false, errors: ["Too short"] }
61
62
// With options
63
const result4 = await validate("", "required", {
64
name: "email",
65
label: "Email Address"
66
});
67
// Result: { valid: false, errors: ["Email Address is required"] }
68
```
69
70
### validateObject Function
71
72
Validates an entire object against a schema of field validation rules.
73
74
```typescript { .api }
75
/**
76
* Validates an object against a schema of field validation rules
77
* @param schema - Object mapping field paths to validation rules
78
* @param values - Object to validate
79
* @param options - Optional configuration for field names and bails behavior
80
* @returns Promise resolving to form validation result
81
*/
82
function validateObject<TValues extends GenericObject, TOutput extends GenericObject = TValues>(
83
schema: RawFormSchema<TValues>,
84
values: TValues,
85
options?: {
86
names?: Record<string, string>;
87
bailsMap?: Record<string, boolean>;
88
}
89
): Promise<FormValidationResult<TValues, TOutput>>;
90
91
type RawFormSchema<TValues> = Record<Path<TValues>, string | GenericValidateFunction | GenericObject>;
92
93
interface FormValidationResult<TInput extends GenericObject, TOutput extends GenericObject = TInput> {
94
valid: boolean;
95
results: Partial<FlattenAndMapPathsValidationResult<TInput, TOutput>>;
96
errors: Partial<Record<Path<TInput>, string>>;
97
values?: Partial<TOutput>;
98
source: 'schema' | 'fields' | 'none';
99
}
100
```
101
102
**Usage Examples:**
103
104
```typescript
105
import { validateObject } from "vee-validate";
106
107
// Object validation with function rules
108
const userSchema = {
109
name: (value) => value ? true : "Name is required",
110
email: (value) => {
111
if (!value) return "Email is required";
112
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) return "Email is invalid";
113
return true;
114
},
115
age: (value) => {
116
if (!value) return "Age is required";
117
if (value < 18) return "Must be at least 18";
118
return true;
119
}
120
};
121
122
const userData = {
123
name: "John Doe",
124
email: "invalid-email",
125
age: 16
126
};
127
128
const result = await validateObject(userSchema, userData);
129
/*
130
Result: {
131
valid: false,
132
errors: {
133
email: "Email is invalid",
134
age: "Must be at least 18"
135
},
136
results: {
137
name: { valid: true, errors: [] },
138
email: { valid: false, errors: ["Email is invalid"] },
139
age: { valid: false, errors: ["Must be at least 18"] }
140
},
141
source: "fields"
142
}
143
*/
144
145
// With custom field names
146
const resultWithNames = await validateObject(userSchema, userData, {
147
names: {
148
name: "Full Name",
149
email: "Email Address",
150
age: "Age"
151
}
152
});
153
154
// Nested object validation
155
const nestedSchema = {
156
"user.name": (value) => value ? true : "User name is required",
157
"user.profile.bio": (value) => value.length <= 500 || "Bio too long"
158
};
159
160
const nestedData = {
161
user: {
162
name: "",
163
profile: { bio: "A very long bio..." }
164
}
165
};
166
167
const nestedResult = await validateObject(nestedSchema, nestedData);
168
```
169
170
## Validation Rule Types
171
172
### String Rules
173
174
String-based validation rules that reference globally defined rules.
175
176
```typescript { .api }
177
// String rule format: "ruleName" or "ruleName:param1,param2"
178
type StringRule = string;
179
```
180
181
### Function Rules
182
183
Custom validation functions for specific validation logic.
184
185
```typescript { .api }
186
/**
187
* Generic validation function that returns true for valid, or error message(s) for invalid
188
*/
189
type GenericValidateFunction<TValue = unknown> = (
190
value: TValue,
191
ctx: FieldValidationMetaInfo
192
) => MaybePromise<boolean | MaybeArray<string>>;
193
194
interface FieldValidationMetaInfo {
195
field: string;
196
name: string;
197
label?: string;
198
form: Record<string, unknown>;
199
rule?: {
200
name: string;
201
params?: Record<string, unknown> | unknown[];
202
};
203
}
204
```
205
206
### Object Rules
207
208
Rules defined as objects with parameters for built-in validators.
209
210
```typescript { .api }
211
// Object rule format for parameterized validation
212
type ObjectRule = Record<string, unknown>;
213
214
// Example: { required: true, min: 3, max: 50 }
215
```
216
217
### Schema Rules
218
219
TypedSchema interface for integration with validation libraries like Yup, Zod, Joi.
220
221
```typescript { .api }
222
interface TypedSchema<TInput = any, TOutput = TInput> {
223
__type: 'VVTypedSchema';
224
parse(values: TInput, context?: TypedSchemaContext): Promise<{ value?: TOutput; errors: TypedSchemaError[] }>;
225
cast?(values: Partial<TInput>): TInput;
226
describe?(path?: Path<TInput>): Partial<TypedSchemaPathDescription>;
227
}
228
229
interface TypedSchemaContext {
230
formData: GenericObject;
231
}
232
233
interface TypedSchemaError {
234
path?: string;
235
errors: string[];
236
}
237
238
interface TypedSchemaPathDescription {
239
required: boolean;
240
exists: boolean;
241
}
242
```
243
244
## Error Handling
245
246
All validation functions handle errors gracefully and provide structured error information:
247
248
```typescript { .api }
249
// Validation errors are always returned as arrays of strings
250
type ValidationErrors = string[];
251
252
// Form validation provides detailed error mapping
253
type FormErrors<TValues extends GenericObject> = Partial<Record<Path<TValues> | '', string | undefined>>;
254
type FormErrorBag<TValues extends GenericObject> = Partial<Record<Path<TValues> | '', string[]>>;
255
```
256
257
**Error Handling Examples:**
258
259
```typescript
260
import { validate, validateObject } from "vee-validate";
261
262
// Single field error handling
263
try {
264
const result = await validate("", "required");
265
if (!result.valid) {
266
console.log("Validation errors:", result.errors);
267
// Handle validation errors
268
}
269
} catch (error) {
270
console.log("Validation failed:", error);
271
// Handle unexpected errors
272
}
273
274
// Object validation error handling
275
try {
276
const result = await validateObject(schema, data);
277
if (!result.valid) {
278
Object.entries(result.errors).forEach(([field, error]) => {
279
console.log(`${field}: ${error}`);
280
});
281
}
282
} catch (error) {
283
console.log("Schema validation failed:", error);
284
}
285
```