我正在尝试使用Vuelidate
来控制表单的输入。我正在为客户的firstname
,lastname
,nationality
和age
提供一个输入字段。
在我的应用程序中,有必要检查第一个客户是否至少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属性的第一个元素?
答案 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
}
}
}
}
}