以下函数验证表单的字段:
validateFields () {
let invalidFields = []
utils.eachDeep(this.schema, field => {
if (!field.validation) return // don't validate
else if (field.validation.isRequired && !field.value) {
field.errorMessage = 'Required field error'
invalidFields.push(field)
} else if (field.validation.minLength && field.value.length < field.validation.minLength) {
field.errorMessage = 'Minimum length error'
invalidFields.push(field)
} else {
// no errors
field.errorMessage = ''
}
})
invalidFields.length > 0
? this.isFormValid = false
: this.isFormValid = true
}
正如您所看到的,我在每个invalidFields.push(field)
语句中重复else if
。我该如何防止这种情况?
答案 0 :(得分:2)
如果您只想删除else if块中的push(),可以这样做:
validateFields () {
let invalidFields = []
utils.eachDeep(this.schema, field => {
field.errorMessage = '';
if (!field.validation) return // don't validate
else if (field.validation.isRequired && !field.value) {
field.errorMessage = 'Required field error'
} else if (field.validation.minLength && field.value.length < field.validation.minLength) {
field.errorMessage = 'Minimum length error'
}
if(field.errorMessage){
invalidFields.push(field)
}
})
invalidFields.length > 0
? this.isFormValid = false
: this.isFormValid = true
}