javascript 如何显示输入中的表单验证错误,而不是在弹出窗口中逐个显示?

ars1skjm  于 2023-01-01  发布在  Java
关注(0)|答案(1)|浏览(129)

我有一个非常简单的形式在这里与2个必需的输入。
当你点击提交按钮而不填写他们-有弹出窗口说,你应该这样做。问题是,弹出窗口显示一个接一个-例如,如果两个输入未填写,只有第一个输入将有此弹出窗口。当第一个只填写然后它去第二个,反之亦然。
是否有办法在验证期间同时显示所有未填写/填写不正确的字段?以便用户立即看到他/她必须填写的所有内容?
我是个新手,所以请帮助我在纯JS中找到解决方案(如果是关于JS的话)。

<html lang="eng">

<head>
    <title>Title</title>
    <meta content="width=device-width, initial-scale=1" name="viewport" />
</head>

<body>
    <form id="mainForm" action="#" method="POST">
        <div>
            <div>
                <label for="first_name" title="first_name">First name<span class="mandatory">*</span></label>
                <input id="first_name" name="first_name" type="text" value="" required=""
                    oninvalid="setCustomValidity('Enter first name')" oninput="setCustomValidity('')"
                    placeholder="Enter first name">
                <p class="error_message"></p>
            </div>
            <div>

                <label for="lastName" title="lastName">Last name<span class="mandatory">*</span></label>
                <input id="lastName" name="lastName" type="text" value="" required=""
                    oninvalid="setCustomValidity('Enter last name')" oninput="setCustomValidity('')"
                    placeholder="Enter last name">
                <p class="error_message"></p>
            </div>

            <div class="">
                <input class="email_btn btn btn-block" type="submit" value="Submit">
            </div>
        </div>
    </form>
</body>

</html>
z2acfund

z2acfund1#

您提供的代码使用了JavaScript的内置函数setCustomValidity()。这很可能是弹出窗口的原因。相反,我们可以编写一个自定义函数来显示带有文本的小段落/span。
这里我们有一个HTML表单,但是在单击Submit按钮时调用了自定义函数validateFields()

<form class="" action="your-post-page.html" method="post" id="my-form-id" name="my-form-name" onsubmit="return validateFields()" target="_blank" class="validate" novalidate="">

    <input id="name_1" type="text">
    <br><br>
    <input id="name_2" type="text">
    <br><br>
    <input id="name_3" type="text">
    <br><br>

    <input type="submit" name="" value="SUBMIT FORM">
</form>
<p id="error_messages" style="background-color: red; color: white;"></p>

让它发生的JS:
(* 自定义函数,对输入为空做出React,并让用户知道哪些字段需要修复,将代码放在html-page中的</html>标记之前 *)

<script type="text/javascript">

    function validateFields() {

        // reference to the message paragraph we aim to fill with error messages.
        var error_text_output_element = document.getElementById("error_messages");

        var fields_to_check = ["name_1", "name_2", "name_3"]; // enter the IDs of all fields you want to check for errors in this list.
        var fields_human_names = ["Name 1", "Name 2", "Name 3"]; // these are just the human readable names for the fields.

        var check_field;
        var error_message = "Errors occurred, please fill in these fields: "; // setting basic text here.
        var errors_exist = 0;

        for (var i = 0; i < fields_to_check.length; i++) {

            check_field = document.forms["my-form-id"][fields_to_check[i]].value;

            if (check_field == "") {

                if (errors_exist === 0) {
                    error_message += fields_human_names[i];  // first time we add a field, no comma.
                } else {
                    error_message += ", " + fields_human_names[i]; // for each field that was empty, add the field and the comma.
                }

                errors_exist += 1; // increment with one for each error that occurs.
            }

        }

        if (errors_exist > 0) { // only output error messages or stop the form if any fields are empty.

            error_text_output_element.innerHTML = error_message;
            return false; // stops the sending of the form in the post procedure.
        }

    } // end message_class function.

</script>

最后,这里是您自己的代码,包含以下示例:

<html lang="eng">
<head>
    <title>Title</title>
    <meta content="width=device-width, initial-scale=1" name="viewport" />
</head>
<body>
    <form id="mainForm" action="#" method="POST" onsubmit="return validateFields()" >
        <div>
            <div>
                <label for="first_name" title="first_name">First name<span class="mandatory">*</span></label>
                <input id="first_name" name="first_name" type="text" value="" placeholder="Enter first name">
                <p class="error_message"></p>
            </div>
            <div>

                <label for="lastName" title="lastName">Last name<span class="mandatory">*</span></label>
                <input id="lastName" name="lastName" type="text" value="" placeholder="Enter last name">
                <p class="error_message"></p>
            </div>

            <div class="">
                <input class="email_btn btn btn-block" type="submit" value="Submit">
            </div>
            <!-- here I added a new box for the error messages in your code -->
            <div class="">
                <p id="error_messages" style="background-color: red; color: white;"></p>
            </div>
        </div>
    </form>
</body>

<script type="text/javascript">

    function validateFields() {

        // reference to the message paragraph we aim to fill with error messages.
        var error_text_output_element = document.getElementById("error_messages");

        var fields_to_check = ["first_name", "lastName"]; // enter the IDs of all fields you want to check for errors in this list.
        var fields_human_names = ["First name", "Last name"]; // these are just the human readable names for the fields.

        var check_field;
        var error_message = "Errors occurred, please fill in these fields: "; // setting basic text here.
        var errors_exist = 0;

        for (var i = 0; i < fields_to_check.length; i++) {

            check_field = document.forms["mainForm"][fields_to_check[i]].value;

            if (check_field == "") {

                if (errors_exist === 0) {
                    error_message += fields_human_names[i];  // first time we add a field, no comma.
                } else {
                    error_message += ", " + fields_human_names[i]; // for each field that was empty, add the field and the comma.
                }

                errors_exist += 1; // increment with one for each error that occurs.
            }

        }

        if (errors_exist > 0) { // only output error messages or stop the form if any fields are empty.

            error_text_output_element.innerHTML = error_message;
            return false; // stops the sending of the form in the post procedure.
        }

    } // end message_class function.

</script>

</html>

这是通过自定义脚本来获得一个可以设置样式和增强自己的框,在本例中位于表单下方。(由于浏览器的不同,样式可能不统一)您也可以删除原始代码中的JavaScript函数setCustomValidity(''),这样就只剩下一个使用已有属性required=""的通用消息,它产生了这个:

要实现这种行为,请将每个字段的标记更改为如下所示:

<input id="first_name" name="first_name" type="text" value="" required="" placeholder="Enter first name">

相关问题