vuejs3yupvee-validate

Vee-validate with yup nested object not showing errors (not validating nested objects)


So I have this setup using vee-validate and yup.

import { useForm } from 'vee-validate'
import * as yup from 'yup'

const {
  values,
  errors,
  defineComponentBinds,
  isSubmitting,
  setFieldValue,
  handleSubmit
} = useForm({
  validationSchema: yup.object({
    field0: yup.string().label('Field 0').required(),
    testFields: yup.object().shape({
      field1: yup.string().label('Field 1').required()
    })
  })
})

const field0 = defineComponentBinds('field0')
const testFields = ref({
  field1: defineComponentBinds('field1')
})

In my template:

<pre>{{ field0 }}</pre>
<InputText
 v-bind="field0"
 class="w-full border-left-3 border-red-600"
/>
<pre>{{ testFields }}</pre>
<InputText
 v-bind="testFields.field1"
 class="w-full border-left-3 border-red-600"
/>

The problem is field1 which is inside the object testFields is not showing errors even it is set to required(). Upon testing to top level, field0 works just fine. I don't know what I have missed but it seems the nested input is not validating properly.

enter image description here


Solution

  • A silly mistake. This should be:

    const field1 = defineComponentBinds('testFields.field1')
    <InputText
     v-bind="field1"
     class="w-full border-left-3 border-red-600"
    />
    

    or (if you are working with dynamic fields)

    const testFields = ref({
      field1: defineComponentBinds('testFields.field1')
    })
    <InputText
     v-bind="testFields.field1"
     class="w-full border-left-3 border-red-600"
    />
    

    As the documentation stated here