Search code examples
vue.jsvuetify.jsvuelidate

How to use vuelidate with vuetify 2 for nested data? Getting invalid field


I'm trying to use vuelidate with Vuetify 2 but im getting into trouble when trying to validate a nested object value.

This code works fine:

    <template>
        <v-text-field
        v-model="no_nome"
        :error-messages="nameErrors"
        label="Nome"
        @input="$v.no_nome.$touch()"
        @blur="$v.no_nome.$touch()"
        >
        </v-text-field>
    </template>

    <script>

     import { required } from 'vuelidate/lib/validators'
     export default {

        data() {
            return {
                no_nome:'',
            }
        },
        validations: {
            no_nome: {
                required
            },
        },
        computed: {
            nameErrors () {
                const errors = []
                if (!this.$v.no_nome.$dirty)
                    return errors
                !this.$v.no_nome.required && errors.push('Name is required.')
                return errors
            },
        }
     }
   </scrip>

But if i change my no_nome data to:

        data() {
            return {
                user : {
                   no_nome:'',
                }
            }
        },

and

        <v-text-field
        v-model="user.no_nome"
        :error-messages="nameErrors"
        label="Nome"
        @input="$v.no_nome.$touch()"
        @blur="$v.no_nome.$touch()"
        >
        </v-text-field>

after running $vm0.$v.no_nome.$touch(), $vm0.$v.no_nome.$invalid will always return true even when user.no_nome is not empty. How can i make the validation works for user.no_nome and any other nested data value?


Solution

  • You have to use the same data shape between your data and your validations. See Data Nesting.

    So your validations must be:

    validations: {
      user: {
        no_nome: {
          required
        }
      }
    }
    

    and

    computed: {
      nameErrors () {
        const errors = []
        if (!this.$v.user.no_nome.$dirty)
          return errors
        !this.$v.user.no_nome.required && errors.push('Name is required.')
        return errors
      }
    }
    

    and

    <v-text-field
      v-model="user.no_nome"
      :error-messages="nameErrors"
      @input="$v.user.no_nome.$touch()"
      @blur="$v.user.no_nome.$touch()"/>
    

    Example