简体   繁体   中英

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

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.

My Form Code:

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

My JavaScript validation method:

<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()'"

You must add the .value , when you use document.getElementById, you get the entire HTML element.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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