如何防止在else if语句中重复赋值?

时间:2017-05-26 02:20:12

标签: javascript if-statement

以下函数验证表单的字段:

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。我该如何防止这种情况?

1 个答案:

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