I have a form where certain fields are inside an object:
<script setup lang="ts">
...
const schema: yup.SchemaOf<any> =
yup.object({
group: yup.string().nullable().required(),
description: yup.string().nullable().required(),
user: yup
.object({
first_name: yup.string().required(),
last_name: yup.string().required(),
})
.required(),
})
const { errors, handleSubmit, isSubmitting } = useForm({
validationSchema: schema,
initialValues: {
group: '',
description: '',
user: {}
},
});
const { value: group } = useField<string>('group');
const { value: description } = useField<string>('description');
const { value: user } = useField<any>('user');
const isValid = useIsFormValid();
...
</script>
<template>
<div>
<label for="group">Group:</label
><input id="group" v-model="group" type="text" />
</div>
<div>
<label for="description">Description:</label
><input id="description" v-model="description" type="text" />
</div>
<div>
<label for="first-name">First name</label
><input id="first-name" v-model="user.first_name" type="text" />
</div>
<div>
<label for="last-name">Last name</label
><input id="last-name" v-model="user.last_name" type="text" />
</div>
<button :disabled="!isValid">Save</button>
...
</template>
But the data validation of this object is only done after changing a field outside of it, i.e. fill in group
, description
, first_name
, last_name
(in this same order) and the form will NOT be considered valid, only if you edit group
or description
again.
How can I make the validation be done when I change the field myself?
Here is the link to the complete code.
I am using the following versions:
"vue":"^3.2.37",
"vee-validate": "^4.5.11",
"yup": "^0.32.11"
CodePudding user response:
When you use useField() with an Object, the nested properties lose their reactivity connection. So here are two options to resolve this: wrap useField with reactive() or use useField() for each nested property separately.
option 1
const { value: user } =reactive(useField('user'));
option 2
const { value: first_name } = useField('user.first_name');
const { value: last_name } = useField('user.last_name');
here is a working example here