Home  >  Q&A  >  body text

Validate fields of objects in form - Vue 3 + Vee-validate + yes

I have a form where some 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 its external fields, i.e. filling in group, description, first_name, last_name (in the same order), and the form will not be considered valid only if you edit group or description again.

How do I validate when I change a field myself?

Here is the link to the complete code.

I use the following version:

"vue":"^3.2.37",
"vee-validate": "^4.5.11",
"yup": "^0.32.11"


P粉486138196P粉486138196359 days ago738

reply all(1)I'll reply

  • P粉191610580

    P粉1916105802023-11-17 00:47:41

    When you use useField() with an object, nested properties lose their reactive connections. So here are two options to solve this problem: wrap useField with reactive() or use separate useField() for each nested property.

    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 exampleHere< /p>

    reply
    0
  • Cancelreply