简体   繁体   English

表单“提交”事件不等待验证 function 返回

[英]form "onsubmit" event doesn't wait for the validation function return

I have an html basic form in which I have some fields to validate before the form is finally submitted, however, even having my validation function being called by the "onsubmit" event of my form it doesn't actually perform before the submitting is completed.我有一个 html 基本表单,在最终提交表单之前我有一些字段需要验证,但是,即使我的验证 function 被我表单的“onsubmit”事件调用,它在提交完成之前实际上并没有执行. In the end, I get lots of errors coming from my backend due to invalid data that was sent by the html form even before the validation method finishes.最后,由于 html 表单发送的无效数据甚至在验证方法完成之前,我的后端出现了很多错误。

Debugging my page by the devtools in my browser I can see that my validation function is called, however, the submission occurs like if it was async very similar to an ajax call.在我的浏览器中通过 devtools 调试我的页面我可以看到我的验证 function 被调用,但是,提交的发生就像它是异步的,非常类似于 ajax 调用。

My Form Code:我的表格代码:

<form id="frmOrder" onsubmit="return val();">
</form>

My JavaScript validation method:我的JavaScript验证方法:

<script type="text/javascript">

        function val() {
            var phone = document.getElementById("inputPhone");
            var date = document.getElementById("inputdate");

            if (phone.length < 10) {
                return false;
            }
         
            return true;
        };
    </script>

I've tried different triggers like: using a <button> tag with a type ="submit" Or calling the method by the onsubmit event without return "onsubmit='validate()'"我尝试了不同的触发器,例如:使用type ="submit"<button>标记,或者通过 onsubmit 事件调用方法而不返回 "onsubmit='validate()'"

You must add the .value , when you use document.getElementById, you get the entire HTML element.您必须添加.value ,当您使用 document.getElementById 时,您将获得整个 HTML 元素。

    var phone = document.getElementById("inputPhone").value;

    var date = document.getElementById("inputdate").value;

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

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