'How can I use Vuelidate to validate an empty collection?

I am trying to use the same form for create and update. Everything is working great when I am updating an existing location. It's when I am creating a new location that my validation is causing an error.

I can understand why it's unhappy, I don't have anything to validate. I don't understand what I am doing wrong though.

Looking at the docs, I believe I'm setting up the validation rule properly:

location: {
    messaging: {
        $each: {
          email: {
            fromName: { required },
            fromAddress: { required },
         },
     },
  },
  ...
}

I am passing location in as props with a default of:

...
messaging: [{
    email: {
        fromName: '',
        fromAddress: '',
      },
}],

When saving the data, it has the correct shape I'm looking for as well:

[{"email":{"fromName":"No Reply <[email protected]>","fromAddress":"[email protected]"}}]

My input looks like this:

<input id="fromName" 
    v-model.trim="$v.location.messaging.$each[0].email.fromName.$model"
    type="text"
    ...

The error I am getting is

Cannot read properties of undefined (reading 'email')"

I understand that email is undefined, nothing exists (yet). How can I set up the validation collection so it knows what email is?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source