使用JavaScript时停止提交表单

问题描述:

我有一个表单,如果该数字小于15,则用户输入一个cnic编号,然后提醒一个消息,并停止表单提交,但问题是,当 cnic 编号较小时,表单提交无法停止大于15.

I have a form where user enter a cnic number if this number is less than 15 then alert a msg and stop the form submission but issue is that form submission cannot stop when the cnic number is less than 15.

<script>
    function validateform()
    {

        var cnic1 = document.getElementById("cnic1").value;
        if (cnic1.length < 15)
        {
            window.alert("Invalid CNIC");
            cnic1.focus();
            return false;
        }
    }
</script>

<form class="col s12" action="tabs.php" method="post" enctype="multipart/form-data" name="applyform">

    <div class="row">
        <div class="input-field col s1"></div>
        <div class="input-field col s4"><label>CNIC No. </label>
            <font style="color: #ff0000">*</font>
        </div>
        <div class="input-field col s6">
            <input id="cnic1" name="cnic1" type="text" value="<?php echo $RowAcc['cnic'];?>" maxlength="15" placeholder="CNIC #" required>
        </div>
    </div>
</form>

tabs.php 页面上写的php提交代码是否存在问题,这就是为什么表单仍在提交过程?

Is there issue in php submission code write on tabs.php page that's why form still submitting process?

您不必返回 false 即可停止提交表单.您需要使用事件的 preventDefault()方法,如果数据有效,则使用JS提交表单.像这样:

You don't have to return false to stop the form from being submitted. You need to use the event's preventDefault() method, and submit the form using JS if the data is valid. Like this:

function validateform(e) { // take the event as parameter
    e.preventDefault(); // stop the submission

    var cnic1 = document.getElementById("cnic1");

    if (cnic1.value.length < 15) {
        window.alert("Invalid CNIC");
        cnic1.focus();
    } else {
        form.submit();
    }
}

var form = document.getElementsByName('applyform')[0];
form.addEventListener('submit', validateform);

我还使用JS添加了侦听器,因此您可以确保将事件参数传递给您的验证函数.从表单中删除 onsubmit ="..." .

I also added the listener using JS just so you can be sure the event parameter is passed to your validation function. Remove the onsubmit="..." from your form.