javascript - JS->对输入进行表单验证。使用for循环获取所有输入索引

标签 javascript html forms validation

我有一个包含 4 个输入的表单,我想在提交时显示警报。我所做的是,我已经创建了在每个输入下显示的警告:display:none;在CSS中。

之后,我在 JS 中创建了一个 for 循环来获取每个输入的索引,并应用我的 if 语句来显示警报 if === null || ===“” 使用变量来生成 querySelector("THE CLASS").style.display="block";

我的表格上也有这一行

<form method="post" class="q-form" name="form" onsubmit="return validate()">

我的问题是,当我提交表单时,显示的唯一警报是用户名下的警报,出现后它也会消失,因为我认为 for 循环会转到下一个输入。

如果还有什么需要澄清的,请告诉我。

这里有所有代码:https://jsbin.com/kazopahuga/1/edit?html,js,output

如果您想查看显示的警报,请按 Run with JS

谢谢!

最佳答案

我建议对您的 validare() 函数进行一些修改:

添加一个标志,指示整个表单是否有效,假设它是正确的,直到找到无效的输入。返回此标志的值。

var isValid = true;

也捕获您的验证消息,以便您可以像输入一样通过索引访问它们:

messages = document.getElementsByClassName('警报警报-危险自定义');

当您发现无效输入时,显示相关消息并将有效标志更新为 false。

if (currentInputValue == null || currentInputValue === "") {
    messages[index].style.display = "block";
    isValid = false;
}

这是更新后的功能:

function validare() {

    var inputs, messages, index;
    var isValid = true;

    inputs = document.getElementsByTagName('input');
    messages = document.getElementsByClassName(' alert alert-danger custom');

    for (index = 0; index < inputs.length; ++index) {
        var currentInputValue = inputs[index].value;
        if (currentInputValue == null || currentInputValue === "") {
            messages[index].style.display = "block";
            isValid = false;
        }
    }

    return isValid;
}

Updated jsbin here

关于javascript - JS->对输入进行表单验证。使用for循环获取所有输入索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38233301/

相关文章:

javascript - 使用 jquery 更改复选框的样式

php - 将 worldpay 示例拼接在一起

html - 移动页面全 Angular - 带图标的居中文本

django - 渲染 : 'WSGIRequest' object has no attribute 'get' 时捕获 AttributeError

css - 超链接按钮

php - 通过 GET 提交表单并保留已有的 GET 参数

javascript - stopPropagation() 提交时不起作用

javascript - 克隆时将数据记录到正确的 html 子元素

javascript - 防止 Controller 创建新的范围对象

c# - 使用 javascript 调用重定向到 ASP.NET MVC 应用程序的操作