[v4] How can I programmatically validate a group of fields? #3828
-
Hi, Vue 3.2.x I want to programatically validate a group of fields in a child component, without submitting the entire form. In the previous version of Vee-validate, if I could do this in <ValidationObserver ref="myRef">
Some form fields here
</ValidationObserver>
<MyButton @click="validateSection" /> and: methods: {
validateSection() {
this.$refs['myRef'].validate().then((res) => {
if (!res) {
// section invalid
} else {
// section valid
}
});
},
}, How can I do this in VeeValidate v4? The above method doesn't work, as The best I have come up with is to emit an event from the child: <MyButton @click="$emit('validate-section')" /> Then use a template <Form
v-slot="{ validateField }"
ref="myForm"
>
...
<Child @validate-section="validateSection" />
</Form> and: methods: {
async validateSection() {
const fields = [ list, of, field, names ];
const valid = await Promise.all(fields.map(async (field) => {
const res = await this.$refs.myForm.validateField(field);
return res.valid;
}));
if(valid.includes(false)) {
// section invalid
} else {
// section valid
}
},
}, This works, but it seems rather hacky and the docs recommend avoiding template Is there a better way to do this in in VeeValidate v4? Thank you for this amazing library 🕶️ |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Sorry I missed this. I would say the best way to do this is with the composition API. Since you have access to So something like this: <script setup>
const { validateField } = useForm({
// validation schema and other options ...
});
function validateGroup() {
// rough example, use map and `promise.all` to be able to await this properly.
['name', 'email', 'password'].forEach(field => validateField(field));
}
</script> |
Beta Was this translation helpful? Give feedback.
Sorry I missed this. I would say the best way to do this is with the composition API. Since you have access to
validateField
you can pretty much do what you want by calling it for each field you want to validate.So something like this: