jeudi 25 mai 2017

How to prevent this repeated assignment in an else if statement?

The following function validates the fields of a form:

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
}

As you can see I'm repeating invalidFields.push(field) in every else if statement. How can I prevent this?

Aucun commentaire:

Enregistrer un commentaire