首页 > 解决方案 > 验证表单并显示警报中未填写的项目

问题描述

我想以这样的方式验证表单,即所有未填写的字段都出现在警报中,如下所示:

https://i.stack.imgur.com/unH29.png

我只能让它们以以下方式出现我填写第一个,而其他人没有,那么只有第二个输入出现在警报中,而不是全部出现,就像我填写第一个和第二个一样,只有第三个输入会出现在警报中,而不是全部

https://i.stack.imgur.com/IUlOD.png

这是我的 JavaScript 代码

function validar() {

    var nome = document.getElementById("nome");
    var cpf = document.getElementById("cpf");
    var data = document.getElementById("data");
    var sexo = document.getElementById("sexo");
    var email = document.getElementById("email");
    var celular = document.getElementById("celular");
    var nivel = document.getElementById("nivel");
    var media = document.getElementById("media").checked;

  
    if (nome.value == "") {
        alert("Nome não informado");

     
        nome.focus();
        
        return;
    }
    if (cpf.value == "") {
        alert("CPF não informado");
        cpf.focus();
        return;
    }
    if (data.value == "") {
        alert("Nascimento não informado");
        data.focus();
        return;
    }
    if (sexo.value == "") {
        alert("Sexo não informada");
        sexo.focus();
        return;
    }
    if (email.value == "") {
        alert("Email não informado");
        email.focus();
        return;
    }
    if (celular.value == "") {
        alert("Celular não informado");
        celular.focus();
        return;
    }
    if (nivel.value == "") {
        alert("Nivel não informado");
        nivel.focus();
        return;
    }
    if (media.value == "") {
        alert("Media não informado");
        media.focus();
        return;
    }
}

标签: javascriptformsvalidationalert

解决方案


首先,让我们稍微清理一下代码。由于您对每个验证都使用相同的格式,因此重用创建十个 if 语句并不完全有意义。

此外,我们可以过滤所有缺少值的元素(AKA Falsey),并根据它们的内部文本将它们映射出来(如果内部文本不等于名称,显然你应该修改它)

const elements = [nome, cpf, data, sexo, email, celular, nivel, media]
const filtered = elements.filter(element => !element.value)
if (filtered.length > 0) {
  filtered.forEach(element => element.focus())
  return alert(filtered.map(element => element.innerText).join('\n'))
}

推荐阅读