简体   繁体   English

如何在弹出窗口中一一显示输入中的表单验证错误?

[英]How to show form validation errors in inputs NOT one by one in popups?

I have a very simple form here with 2 required inputs.我这里有一个非常简单的表格,其中包含 2 个必需的输入。

When you click submit button without filling them - there are popups saying that you should do it.当您单击提交按钮而不填写它们时 - 会有弹出窗口说您应该这样做。 The problem is that popups are showed one by one - for example, if both inputs arent filled, only the first input will have this popup.问题是弹出窗口是一个一个显示的——例如,如果两个输入都没有填充,只有第一个输入会有这个弹出窗口。 And when the first one is filled only then it goes to the second and vice versa.只有当第一个被填满时,它才会进入第二个,反之亦然。

Is there any way to show all the fields that are not filled/filled incorrect during the validation at the same moment?有没有办法在验证期间同时显示所有未填写/填写不正确的字段? So the user sees immediately everything he/she has to fill?所以用户会立即看到他/她必须填写的所有内容?

I am quite new to this, so please help me find the solution in pure JS (if it is about JS).我对此很陌生,所以请帮我找到纯 JS 的解决方案(如果它是关于 JS 的)。 Here is the code:这是代码:

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

The code you provided is using a built in function of JavaScript, setCustomValidity() .您提供的代码使用的是内置 function 的 JavaScript, setCustomValidity() This most likely is the reason for the pop-up.这很可能是弹出窗口的原因。 Instead we can write a custom function to show a little paragraph/span with the text instead.相反,我们可以编写一个自定义的 function 来显示一个带有文本的小段落/跨度。

Here we have a HTML form, but with a call for the custom function validateFields() , when clicking the Submit button:这里我们有一个 HTML 表单,但是在单击提交按钮时调用了自定义 function 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>

The JS that makes it happen:实现它的 JS:

( custom function that reacts to inputs being empty and lets the user know which fields need fixing, put code before the </html> tag in your html-page ) 自定义 function 对输入为空做出反应并让用户知道哪些字段需要修复,将代码放在 html 页面中的</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>

Now lastly, here is your own code with this example:现在最后,这里是你自己的代码与这个例子:

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

That was with custom scripting to get a box that you can style and enhance yourself, in this case below the form.那是通过自定义脚本来获得一个框,您可以设置样式并增强自己的功能,在本例中是在表单下方。 But if you are okay with some default (and perhaps not unified styling, due to browser differences) you can also just remove the JavaScript function you had in your original code, the setCustomValidity('') .但是,如果您接受某些默认设置(由于浏览器差异,可能不统一样式),您也可以删除原始代码中的setCustomValidity('') That will leave you with a generic message using the already present attribute required="" , which produces this:这将为您留下一条使用已经存在的属性required=""的通用消息,它会产生以下内容:

在此处输入图像描述

To achive that behaviour, change your tags for each field to look like this instead:要实现该行为,请将每个字段的标签更改为如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM