0
# Logical Operators
1
2
Combinators for creating complex validation logic by combining multiple validators with logical operations.
3
4
## Capabilities
5
6
### AND Operator
7
8
Combines multiple validators where all must pass for the validation to succeed.
9
10
```javascript { .api }
11
/**
12
* Combines validators with logical AND - all validators must pass
13
* @param validators - Array of validators to combine
14
* @returns ValidationRuleWithoutParams that passes only when all validators pass
15
*/
16
function and<T = unknown>(...validators: ValidationRule<T>[]): ValidationRuleWithoutParams;
17
```
18
19
**Usage Examples:**
20
21
```javascript
22
import { and, required, minLength, alpha } from "@vuelidate/validators";
23
24
// Combine multiple string validators
25
const strictNameValidation = and(
26
required,
27
minLength(2),
28
alpha
29
);
30
31
// Test the combined validator
32
const validName = strictNameValidation("John"); // true (required ✓, length ✓, alpha ✓)
33
const invalidName1 = strictNameValidation(""); // false (required ✗)
34
const invalidName2 = strictNameValidation("A"); // false (minLength ✗)
35
const invalidName3 = strictNameValidation("John123"); // false (alpha ✗)
36
37
// In validation rules
38
const validationRules = {
39
username: {
40
strictValidation: and(
41
required,
42
minLength(3),
43
alphaNum
44
)
45
}
46
};
47
```
48
49
### OR Operator
50
51
Combines multiple validators where at least one must pass for the validation to succeed.
52
53
```javascript { .api }
54
/**
55
* Combines validators with logical OR - at least one validator must pass
56
* @param validators - Array of validators to combine
57
* @returns ValidationRuleWithoutParams that passes when any validator passes
58
*/
59
function or<T = unknown>(...validators: ValidationRule<T>[]): ValidationRuleWithoutParams;
60
```
61
62
**Usage Examples:**
63
64
```javascript
65
import { or, email, url, numeric } from "@vuelidate/validators";
66
67
// Allow either email or URL format
68
const emailOrUrl = or(
69
email,
70
url
71
);
72
73
// Test the combined validator
74
const validEmail = emailOrUrl("user@example.com"); // true (email ✓)
75
const validUrl = emailOrUrl("https://example.com"); // true (url ✓)
76
const invalidBoth = emailOrUrl("invalid-format"); // false (both ✗)
77
78
// Complex OR combination
79
const flexibleIdValidation = or(
80
numeric,
81
and(alpha, minLength(5))
82
);
83
84
// In validation rules
85
const validationRules = {
86
contactInfo: {
87
emailOrUrl: or(email, url)
88
},
89
identifier: {
90
flexibleId: or(
91
numeric,
92
and(alpha, minLength(3))
93
)
94
}
95
};
96
```
97
98
### NOT Operator
99
100
Negates a validator result - passes when the wrapped validator fails.
101
102
```javascript { .api }
103
/**
104
* Negates validator result - passes when wrapped validator fails
105
* @param validator - Validator to negate
106
* @returns ValidationRuleWithoutParams that passes when wrapped validator fails
107
*/
108
function not<T = unknown>(validator: ValidationRule<T>): ValidationRuleWithoutParams;
109
```
110
111
**Usage Examples:**
112
113
```javascript
114
import { not, numeric, email, required } from "@vuelidate/validators";
115
116
// Must NOT be numeric (e.g., for username field)
117
const notNumeric = not(numeric);
118
119
// Test the negated validator
120
const validUsername = notNumeric("john_doe"); // true (not numeric ✓)
121
const invalidUsername = notNumeric("12345"); // false (is numeric ✗)
122
123
// Must NOT be an email (for security code field)
124
const notEmail = not(email);
125
126
// Complex negation
127
const notRequiredOrEmpty = not(required);
128
129
// In validation rules
130
const validationRules = {
131
username: {
132
required: required,
133
notNumeric: not(numeric)
134
},
135
displayName: {
136
notEmail: not(email)
137
},
138
optionalField: {
139
canBeEmpty: not(required) // This allows empty values
140
}
141
};
142
```
143
144
## Complex Logical Combinations
145
146
### Nested Logical Operations
147
148
Logical operators can be nested to create sophisticated validation logic:
149
150
```javascript
151
import { and, or, not, required, minLength, maxLength, alpha, numeric, email } from "@vuelidate/validators";
152
153
// Complex username validation:
154
// - Required AND
155
// - (Alphanumeric with 3-20 chars) OR (Email format)
156
// - NOT purely numeric
157
const complexUsernameValidation = and(
158
required,
159
or(
160
and(alphaNum, minLength(3), maxLength(20)),
161
162
),
163
not(numeric)
164
);
165
166
// Password complexity:
167
// - Required AND
168
// - Minimum 8 characters AND
169
// - NOT purely alphabetic AND NOT purely numeric
170
const passwordComplexity = and(
171
required,
172
minLength(8),
173
not(alpha),
174
not(numeric)
175
);
176
```
177
178
### Conditional Logic Patterns
179
180
```javascript
181
import { and, or, not, required, requiredIf, email, url } from "@vuelidate/validators";
182
183
// Business contact validation:
184
// - If business account: require company email OR company website
185
// - If personal account: just require email
186
const businessContactValidation = or(
187
and(
188
requiredIf(computed(() => accountType.value === "business")),
189
or(
190
and(email, /* custom business email validator */),
191
url
192
)
193
),
194
and(
195
requiredIf(computed(() => accountType.value === "personal")),
196
197
)
198
);
199
```
200
201
### Multi-Field Dependencies
202
203
```javascript
204
import { and, or, required, requiredIf, sameAs } from "@vuelidate/validators";
205
206
const formData = ref({
207
hasAlternateContact: false,
208
primaryEmail: "",
209
alternateEmail: "",
210
phone: ""
211
});
212
213
const validationRules = {
214
primaryEmail: { required, email },
215
216
// Alternate contact must be provided if checkbox is checked
217
// AND it must be either email OR phone
218
// AND if email is provided, it must NOT be same as primary
219
alternateContact: {
220
validation: and(
221
requiredIf(computed(() => formData.value.hasAlternateContact)),
222
or(
223
and(
224
email,
225
not(sameAs(computed(() => formData.value.primaryEmail)))
226
),
227
phone // Assuming phone validator exists
228
)
229
)
230
}
231
};
232
```
233
234
## Best Practices
235
236
### Readability and Maintenance
237
238
```javascript
239
// Good: Break complex logic into named validators
240
const hasValidLength = and(minLength(3), maxLength(50));
241
const hasValidFormat = or(alphaNum, email);
242
const isNotRestricted = not(in(RESTRICTED_WORDS));
243
244
const usernameValidation = and(
245
required,
246
hasValidLength,
247
hasValidFormat,
248
isNotRestricted
249
);
250
251
// Less readable: Deeply nested inline
252
const usernameValidation2 = and(
253
required,
254
and(minLength(3), maxLength(50)),
255
or(alphaNum, email),
256
not(in(RESTRICTED_WORDS))
257
);
258
```
259
260
### Error Message Considerations
261
262
```javascript
263
import { helpers } from "@vuelidate/validators";
264
265
// Custom messages for complex logical validators
266
const complexValidation = helpers.withMessage(
267
"Username must be 3-20 characters, alphanumeric or email format, and not purely numeric",
268
and(
269
required,
270
or(
271
and(alphaNum, minLength(3), maxLength(20)),
272
273
),
274
not(numeric)
275
)
276
);
277
```
278
279
### Performance Optimization
280
281
```javascript
282
// Efficient: Put most likely to fail validators first
283
const efficientValidation = and(
284
required, // Most likely to fail, check first
285
minLength(8), // Quick length check
286
expensiveCustomValidator() // Expensive operation last
287
);
288
289
// Less efficient: Expensive operations first
290
const inefficientValidation = and(
291
expensiveCustomValidator(), // Runs even if required fails
292
required,
293
minLength(8)
294
);
295
```