使用通用模式提高多个if语句的可读性

时间:2018-11-28 01:27:52

标签: javascript readability

我正在做一些JavaScript前端,并且我有大量的表单,所有表单都需要验证。到目前为止,我正在使用此结构:

function validateForm() {
    let form = document.forms["form-add-consumer"];

    let id = form["input-id"].value;
    let lastName = form["input-last-name"].value;
    let firstName = form["input-first-name"].value;
    ...

    let missing = false;
    if (lastName.trim() === "") {
        document.getElementById("input-last-name-error").className = "error";
        missing = true;
    }
    if (firstName.trim() === "") {
        document.getElementById("input-first-name-error").className = "error";
        missing = true;
    }

    if(missing){
        return false
    } else {
        return buildRequest(id, firstName, lastName, ...);
    }
}

如您所见,对于大型表格,该功能将快速增长。该代码对于每个字段都有点多余:

  1. 声明表单字段
  2. 根据布尔条件检查其值
  3. 如果布尔值失败,则显示错误标签,并将失败的布尔值设置为true,以不发送请求

如何在不过度复杂的情况下改进此代码(如果可能,则没有库)?

1 个答案:

答案 0 :(得分:1)

也许您可以创建一个包含每个字段验证器的对象,以及用于各个字段的选择器,以便您可以像以下这样更简洁的方式执行必要的验证:

function validateForm() {
    let form = document.forms["form-add-consumer"];

    let id = form["input-id"].value;
    let lastName = form["input-last-name"].value;
    let firstName = form["input-first-name"].value;
    ...

    // Construct an object with selectors for the fields as keys, and 
    // per-field validation functions as values like so
    const fieldsToValidate = {
      '#input-id' : value => value.trim() !== '',
      '#input-last-name' : value => value.trim() !== '',
      '#input-first-name' : value => value.trim() !== '',
      ...,
      '#number-field' : value => parseInt(value) > 0, // Different logic for number field
      ...
    }

    const invalidFields = Object.entries(fieldsToValidate)
    .filter(entry => {

        // Extract field selector and validator for this field
        const fieldSelector = entry[0];
        const fieldValueValidator = entry[1];
        const field = form.querySelector(fieldSelector);

        if(!fieldValueValidator(field.value)) {
            // For invalid field, apply the error class
            field.className = 'error'
            return true;
        }

        return false;
    });

    // If invalid field length is greater than zero, this signifies
    // a form state that failed validation
    if(invalidFields.length > 0){
        return false
    } else {
        return buildRequest(id, firstName, lastName, ...);
    }
}