简体   繁体   English

即使在验证函数返回 false 后,表单仍在提交

[英]Form is submitting even after validation function returning false

This question is asked many times.这个问题被问了很多次。 And I reviewed most of them and the problem in all the cases was.我审查了其中的大部分,所有情况下的问题都是。

  1. They were not writing return before function call onSubmit form.他们没有在函数调用onSubmit表单之前写return

  2. They were using onClick instead of onSubmit .他们使用的是onClick而不是onSubmit

  3. They were returning false inside if statement, so if the if is not true so function returning true and form is submitting.他们在if语句中返回 false,所以如果if不是 true,那么函数返回 true 并且表单正在提交。

But my case different from all the above cases.但我的情况与上述所有情况不同。

HTML: HTML:

<form id="form-box" name="booksUpload" action="action_page.php" onSubmit="return validateForm()">
    /*Various input fields.*/    
</form>

JavaScript: JavaScript:

        <script>
            function validateForm(){

                /*Validating phone numner*/
                var phone = document.forms["booksUpload"]["phone-number"].value;
                var phErr = document.getElementById("phError");

                if(phone.toString().length != 10){
                    phErr.innerHTML = "Enter a valid mobile number (10 digits)";
                }
                else{
                    phErr.innerHTML = "";
                }

                /*Validating Status*/
                var status = document.forms["booksUpload"]["status"];
                var checked = false;
                var statusErr = document.getElementById("statusError");

                for(var i = 0; i < status.length; i++){
                    if(status[i].checked){
                        checked = true;
                        break;  
                    }
                }

                if(checked == false){
                    statusErr.innerHTML = "Select one option \"Old or New\"";
                }

                else{
                    statusErr.innerHTML = "";
                }

                return false;
            }
        </script>

您应该在调用函数之前阻止表单提交

onsubmit="event.preventDefault(); validateForm();"

I think your submit function is correct !我认为您的提交功能是正确的! Just try by writing full html for your function requirement element or id !!!只需尝试为您的功能需求元素或 id 编写完整的 html !

<form id="form-box" name="booksUpload" action="action_page.php" onSubmit="return validateForm()">
    <input type="text" name="phone-number">
    <select name="status"></select>
    <input type="submit"> 
</form>
<p id="phError"></p>
<p id="statusError"></p>

function execution is not reaching till return statement, as something wrong within other statements before return.函数执行直到 return 语句才到达,因为在 return 之前的其他语句中有错误。 When everything works good in function so return` statement will execute and return false and form will not submit当函数中一切正常时, return` 语句将执行并返回 false 并且表单不会提交

In JQuery event.preventDefault() will prevent the default event from occuring, event.stopPropagation() will prevent the event from bubbling up and return false will do both.在 JQuery 中, event.preventDefault()将阻止默认事件发生, event.stopPropagation()将阻止事件冒泡, return false 将两者兼而有之。

In non JQuery return false does not stop the event from bubbling up在非 JQuery 中return false不会阻止事件冒泡

I suggest using HTML5 forms with constraint validation .我建议使用带有约束验证的HTML5 表单。 All modern browsers support it and even for the outdated there are good polyfills.所有现代浏览器都支持它,即使是过时的浏览器也有很好的 polyfills。

Here 'sa small example.这是一个小例子。

<form id="constraint-form" method="post" action="">
    <label for="phone-number">phone number</label>
    <input type="tel" name="phone-number" id="phone-number" value="" pattern="[0-9]{10}" required>

    <input type="submit" name="submit-button" value="submit">
</form>

Just have a try for yourself.自己试试吧。 This small example executes without Javascript and validates the phone number for 10 digits because of its required attribute.这个小例子在没有 Javascript 的情况下执行,并且由于它的必需属性验证了 10 位数字的电话号码。

To push even more, you can use Javascript, to display error messages.要进一步推送,您可以使用 Javascript 来显示错误消息。

<input type="tel" name="phone-number" id="phone-number" value="" pattern="[0-9]{10}" data-valuemissing="Your phone number is required" data-patternmismatch="Please enter digits only. Your phone number needs 10 digits." required>

var form = document.querySelector('#constraint-form');
form.addEventListener('invalid', function(event) {
    event.preventDefault();

    var element = event.target,
        message = element.validationMessage;

    if (element.validity.valueMissing === true && element.dataset.valuemissing !== undefined) {
        message = element.dataset.valuemissing;
    }

    if (element.validity.patternMismatch === true && element.dataset.patternmismatch !== undefined) {
        message = element.dataset.patternmismatch;
    }
}, true);

element.setCustomValidity(message);
alert(message);

This is a small untested example.这是一个未经测试的小例子。 The form tag gets an invalid event listener and triggers if there 's an invalid form element within this form when submitting it.表单标签获取无效事件侦听器,并在提交表单时在此表单中存在无效表单元素时触发。 In this example the phone number input element is required and got its own data attributes as an example how to bind individual error messages to an element.在此示例中,电话号码输入元素是必需的,并获得了自己的数据属性,作为如何将单个错误消息绑定到元素的示例。 When the element is empty or it doesnt match the pattern, one of the error messages will be alerted.当元素为空或与模式不匹配时,将警告其中一条错误消息。

As long there is an invalid form element one cant submit the form.只要有一个无效的表单元素,就不能提交表单。 The magic of constraint validation!约束验证的魔力! ;) ;)

Do not use return inside onsubmit .不要在onsubmit 中使用return

<form id="form-box" name="booksUpload" action="action_page.php" onSubmit="validateForm()">
    /*Various input fields.*/    
</form>

I have been with the same problem but for my case.我遇到了同样的问题,但就我而言。 I was previously using onsubmit but changed to camel case onSubmit and it works.我以前使用过onsubmit但在onSubmit改为驼峰式大小写,并且它有效。

Because you did not accept the answer that suggested you use the event.preventDefault() before calling the validation function I want to suggest that you call the preventDefault in you validation function using因为您没有接受建议您在调用验证函数之前使用event.preventDefault()的答案我想建议您使用

<form id="form-box" name="booksUpload" action="action_page.php" onSubmit="return validateForm(event)">
    /*Various input fields.*/    
</form>

and in your javascript use并在您的 javascript 中使用

<script>
    function validateForm(e){
        ...............
        //call this where ever you want to prevent submission
        e.preventDefault();
        .........
    }

</script>

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

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