Matthias
Matthias

Reputation: 4163

Add custom validator which only applies to first element of $each in vuelidate

I'm trying to use Vuelidate to controll the inputs of my form. I'm providing an input field for the firstname, the lastname, the nationality and the age of the customer.

In my application it's necessary to check if the first customer is at least 18 years old.

I've tried the following to do this:

validations: {
        customers: {
            $each: {
                firstName: { required, minLength: minLength(2), maxLength: maxLength(35) },
                lastName: { required, minLength: minLength(2), maxLength: maxLength(35) },
                nationality: { required }, 
                age: {
                    isFirstCustomerValid: (value) => {
                        return value >= 18
                    }
                }
            }
        }
    }

Now the problem is that this applies to all customers which is not intended. Is there a way to only access the first element of the $each property?

Upvotes: 1

Views: 605

Answers (1)

ittus
ittus

Reputation: 22403

You can try finding customer's index by 2 ways:

  • If you customer has unique id, then use:

      const customerIndex = this.customers.findIndex(c => c.id === customer.id)
    
  • If not, you can try using lodash's method isEqual

    const customerIndex = this.customers.findIndex(c => _.isEqual(c, customer))
    

Code sample:

validations: {
  customers: {
      $each: {
          firstName: { required, minLength: minLength(2), maxLength: maxLength(35) },
          lastName: { required, minLength: minLength(2), maxLength: maxLength(35) },
          nationality: { required }, 
          age: {
              isFirstCustomerValid: (value, customer) => {
                 // if your customer has valid unique id, you can find it by findIndex
                const customerIndex = this.customers.findIndex(c => c.id === customer.id)

                 // OR you ccan try lodash library 'isEqual' method (https://lodash.com/docs/4.17.11#isEqual)
                const customerIndex = this.customers.findIndex(c => _.isEqual(c, customer))

                return customerIndex || value >= 18
              }
          }
      }
  }
}

Upvotes: 1

Related Questions