验证表单并显示警报中未填写的项目

validate form and show the items that were not filled in the alert

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

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;
    }
}

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

此外,我们可以过滤所有缺少值的元素(又名 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'))
}

如果您有不同类型的输入,我认为您可以使用如下简单的解决方案:

function myFunction() {
  const t1 = document.getElementById("t1");
  const t2 = document.getElementById("t2");
  const t3 = document.getElementById("t3");
  
  let msg="";  
        
  if(!t1.value) { // or checked
    msg += "t1 is null \n";
  }
  
  if(!t2.value){
    msg += "t2 is null \n";
  }
  
  if(!t3.value){
    msg += "t3 is null \n";
  }
    
  alert(msg);
}
<html>
<body>

<input type="text" id="t1" />
<br>
<input type="text" id="t2" />
<br>
<input type="text" id="t3" />


<button onclick="myFunction()">Try it</button>
 
</body>
</html>