gpt4 book ai didi

javascript - 提高具有通用模式的多个 if 语句的可读性

转载 作者:行者123 更新时间:2023-11-30 19:59:50 25 4
gpt4 key购买 nike

我正在做一些 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. 根据 bool 条件检查其值
  3. 如果 boolean 失败,显示错误标签并将失败的 boolean 设置为 true 以不发送请求

我怎样才能改进这段代码而不会使它过于复杂(如果可能的话没有库)?

最佳答案

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

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, ...);
}
}

关于javascript - 提高具有通用模式的多个 if 语句的可读性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53510732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com