0
# Conditional and Comparison Validators
1
2
Validators for conditional validation logic and value comparison operations.
3
4
## Capabilities
5
6
### Conditional Required Validators
7
8
Validators that make fields required based on specific conditions or other field values.
9
10
#### Required If Validator
11
12
Makes a field required when a specified condition is true.
13
14
```javascript { .api }
15
/**
16
* Makes field required when condition evaluates to true
17
* @param prop - Condition (boolean, Vue ref, string property path, or function)
18
* @returns ValidationRuleWithoutParams that requires field when condition is true
19
*/
20
function requiredIf(prop: boolean | Ref<boolean> | string | (() => boolean | Promise<boolean>)): ValidationRuleWithoutParams;
21
```
22
23
**Usage Examples:**
24
25
```javascript
26
import { requiredIf } from "@vuelidate/validators";
27
import { ref, computed } from "vue";
28
29
// Static boolean condition
30
const isAdult = ref(false);
31
const adultValidation = requiredIf(isAdult.value);
32
33
// Vue ref condition
34
const showOptionalField = ref(false);
35
const conditionalRequired = requiredIf(showOptionalField);
36
37
// Function condition
38
const requireWhenEmailProvided = requiredIf(() => formData.email !== "");
39
40
// Async function condition
41
const requireWhenServerCheck = requiredIf(async () => {
42
const response = await checkServerCondition();
43
return response.requiresField;
44
});
45
46
// Property path condition (checks sibling property)
47
const requireWhenTypeIsPersonal = requiredIf("personalAccount");
48
49
// In validation rules
50
const validationRules = {
51
accountType: { required },
52
personalDetails: {
53
requiredIf: requiredIf(computed(() => formData.accountType === "personal"))
54
},
55
businessName: {
56
requiredIf: requiredIf(computed(() => formData.accountType === "business"))
57
}
58
};
59
```
60
61
#### Required Unless Validator
62
63
Makes a field required unless a specified condition is true.
64
65
```javascript { .api }
66
/**
67
* Makes field required unless condition evaluates to true
68
* @param prop - Condition (boolean, Vue ref, string property path, or function)
69
* @returns ValidationRuleWithoutParams that requires field unless condition is true
70
*/
71
function requiredUnless(prop: boolean | Ref<boolean> | string | (() => boolean | Promise<boolean>)): ValidationRuleWithoutParams;
72
```
73
74
**Usage Examples:**
75
76
```javascript
77
import { requiredUnless } from "@vuelidate/validators";
78
import { ref, computed } from "vue";
79
80
// Require field unless user is guest
81
const isGuest = ref(false);
82
const requireUnlessGuest = requiredUnless(isGuest);
83
84
// Require unless another field has value
85
const requireUnlessEmailProvided = requiredUnless(() => formData.email !== "");
86
87
// Property path condition
88
const requireUnlessSkipSelected = requiredUnless("skipThis");
89
90
// In validation rules
91
const validationRules = {
92
userType: { required },
93
fullName: {
94
requiredUnless: requiredUnless(computed(() => formData.userType === "anonymous"))
95
},
96
phoneNumber: {
97
requiredUnless: requiredUnless(computed(() => formData.email !== ""))
98
}
99
};
100
```
101
102
### Comparison Validators
103
104
Validators for comparing values between fields or against reference values.
105
106
#### Same As Validator
107
108
Validates that a field value matches another field or reference value.
109
110
```javascript { .api }
111
/**
112
* Validates that field value matches the reference value
113
* @param equalTo - Reference value to compare against (any type or Vue ref)
114
* @param otherName - Optional name for the reference field (for error messages)
115
* @returns ValidationRuleWithParams with equalTo and otherName parameters
116
*/
117
function sameAs<E = unknown>(equalTo: E | Ref<E>, otherName?: string): ValidationRuleWithParams<{ equalTo: E, otherName: string }>;
118
```
119
120
**Usage Examples:**
121
122
```javascript
123
import { sameAs, required } from "@vuelidate/validators";
124
import { ref, computed } from "vue";
125
126
// Password confirmation
127
const formData = ref({
128
password: "",
129
confirmPassword: ""
130
});
131
132
const validationRules = {
133
password: { required },
134
confirmPassword: {
135
required,
136
sameAsPassword: sameAs(computed(() => formData.value.password), "password")
137
}
138
};
139
140
// Email confirmation
141
const emailConfirmation = sameAs(computed(() => formData.value.email), "email");
142
143
// Static value comparison
144
const mustBeTrue = sameAs(true);
145
const mustMatchCode = sameAs("EXPECTED_CODE");
146
147
// Complex object comparison
148
const userData = ref({ id: 123, name: "John" });
149
const mustMatchUser = sameAs(userData.value);
150
151
// In validation with custom field name
152
const validationRules2 = {
153
primaryEmail: { required, email },
154
confirmEmail: {
155
required,
156
email,
157
sameAsPrimary: sameAs(computed(() => formData.value.primaryEmail), "primary email")
158
}
159
};
160
```
161
162
## Advanced Usage Patterns
163
164
### Multi-Step Form Validation
165
166
Conditional validators are particularly useful in multi-step forms where validation rules change based on previous selections:
167
168
```javascript
169
import { required, requiredIf, sameAs, email } from "@vuelidate/validators";
170
import { computed } from "vue";
171
172
const formData = ref({
173
accountType: "",
174
personalInfo: {
175
firstName: "",
176
lastName: "",
177
email: "",
178
confirmEmail: ""
179
},
180
businessInfo: {
181
companyName: "",
182
taxId: ""
183
}
184
});
185
186
const validationRules = {
187
accountType: { required },
188
personalInfo: {
189
firstName: {
190
requiredIf: requiredIf(computed(() => formData.value.accountType === "personal"))
191
},
192
lastName: {
193
requiredIf: requiredIf(computed(() => formData.value.accountType === "personal"))
194
},
195
email: {
196
requiredIf: requiredIf(computed(() => formData.value.accountType === "personal")),
197
198
},
199
confirmEmail: {
200
requiredIf: requiredIf(computed(() => formData.value.personalInfo.email !== "")),
201
email,
202
sameAsEmail: sameAs(computed(() => formData.value.personalInfo.email), "email")
203
}
204
},
205
businessInfo: {
206
companyName: {
207
requiredIf: requiredIf(computed(() => formData.value.accountType === "business"))
208
},
209
taxId: {
210
requiredIf: requiredIf(computed(() => formData.value.accountType === "business"))
211
}
212
}
213
};
214
```
215
216
### Terms and Conditions Validation
217
218
```javascript
219
import { required, requiredIf, sameAs } from "@vuelidate/validators";
220
221
const agreementRules = {
222
agreeToTerms: { sameAs: sameAs(true) },
223
agreeToNewsletter: {}, // Optional
224
parentalConsent: {
225
requiredIf: requiredIf(computed(() => userAge.value < 18)),
226
sameAs: sameAs(true)
227
}
228
};
229
```
230
231
### Dynamic Field Dependencies
232
233
```javascript
234
import { requiredIf, requiredUnless } from "@vuelidate/validators";
235
236
const dynamicRules = {
237
primaryContact: { required },
238
secondaryContact: {
239
requiredUnless: requiredUnless(computed(() => formData.value.primaryContact !== ""))
240
},
241
emergencyContact: {
242
requiredIf: requiredIf(computed(() => formData.value.isMinor || formData.value.hasSpecialNeeds))
243
}
244
};
245
```