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

Javascript 验证表单并显示警报中未填写的项目,javascript,forms,validation,alert,Javascript,Forms,Validation,Alert,我希望以这样一种方式验证表单,即所有未填写的字段都会显示在警报中,如下所示: 我只能让它们以以下方式显示:我填充第一个,其他的不填充,然后只有第二个输入显示在警报中,而不是全部,就像我填充第一个和第二个,只有第三个输入显示在警报中,而不是全部 这是我的javascript代码 function validar() { var nome = document.getElementById("nome"); var cpf = document.getEle

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

我只能让它们以以下方式显示:我填充第一个,其他的不填充,然后只有第二个输入显示在警报中,而不是全部,就像我填充第一个和第二个,只有第三个输入显示在警报中,而不是全部

这是我的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)
如果(过滤的长度>0){
filtered.forEach(element=>element.focus())
返回警报(filtered.map(element=>element.innerText.join('\n'))
}

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

函数myFunction(){
常量t1=document.getElementById(“t1”);
constt2=document.getElementById(“t2”);
const t3=document.getElementById(“t3”);
让msg=“”;
如果(!t1.value){//或选中
msg+=“t1为空\n”;
}
如果(!t2.值){
msg+=“t2为空\n”;
}
如果(!t3.值){
msg+=“t3为空\n”;
}
警报(msg);
}



试试看