javascript - 验证表单并显示警报中未填写的项目
问题描述
我想以这样的方式验证表单,即所有未填写的字段都出现在警报中,如下所示:
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 语句并不完全有意义。
此外,我们可以过滤所有缺少值的元素(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'))
}
推荐阅读
- php - 如何在登录表单中不区分用户名大小写?
- timestamp - from_unixtime 与 from_timestamp 有什么区别
- node.js - 如何正确地将自定义错误从后端(Express)传递到前端(Vue)
- mips - MIPS 功能我对 mips 中的功能有一些疑问
- python - 如何在括号Python 2.7之间提取方程?
- javascript - 诊断未捕获的类型错误:__webpack_require__(...).createServer 不是函数?
- swift - 如何快速继承结构?
- android - 如何从数据源通知存储库/视图模型?
- ruby-on-rails - 在 Rails i18n 本地化中显示日期模式字符串
- reverse-engineering - findExportByName 查找不在模块中的名称