Search code examples
vue.jsvuelidate

How to validate nested objects in Vuelidate?


I use Vuelidate in my project and have the following form:

data () {
  return {
    form: {
      title: undefined,
      users: [{
        name: undefined,
        age: undefined,
      }],
    },
  };
},

I configured validation rules for the "form.title" like so:

validations () {
  return {
    form: {
      title: {
        required,
      },
    },
  };
},

Now, I also need to configure validation for the "form.users" array of objects.

How can I do so?


Solution

  • I found the answer to my question.

    We can validate arrays of objects using the forEach helper.

    import { helpers, required } from '@vuelidate/validators';
    

    The following code works for me with Vuelidate v2.0.0:

    validations () {
      return {
        form: {
          users: {
            $each: helpers.forEach({
              name: {
                required,
              },
              age: {
                required,
              },
            }),
          },
        },
      };
    },