添加自定义验证器,该验证器仅适用于vuelidate中$ each的第一个元素

时间:2019-07-04 19:59:23

标签: javascript vuejs2 vuelidate

我正在尝试使用Vuelidate来控制表单的输入。我正在为客户的firstnamelastnamenationalityage提供一个输入字段。

在我的应用程序中,有必要检查第一个客户是否至少18岁。

我尝试了以下操作:

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
                    }
                }
            }
        }
    }

现在的问题是,这不适用于所有客户。有没有办法只访问$ each属性的第一个元素?

1 个答案:

答案 0 :(得分:0)

您可以尝试通过两种方法查找客户的索引:

  • 如果您的客户具有唯一的ID,请使用:

      const customerIndex = this.customers.findIndex(c => c.id === customer.id)
    
  • 如果没有,您可以尝试使用lodash的方法isEqual

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

代码示例:

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
              }
          }
      }
  }
}