验证失败后仍提交表单

时间:2019-01-07 07:23:14

标签: javascript

即使验证失败,我的表单仍在提交,并且某些特定字段出现警告,需要更正。

function validateForm() {
    var subscriberName = trimAll(document.getElementById("subscriberName").value);

    //Validators like this
    if (subscriberName.length < 1) { alert("Please enter First Name.");
        document.getElementById("subscriberName").focus(); return false; } else { var iChars="_!@#$%^&*()+=-[]\\\';,./{}|\"
        :<>?1234567890";
        var flag = "false";
        for (var i = 0; i < subscriberName.length; i++) { if (iChars.indexOf(subscriberName.charAt(i)) !=-1) {
            alert("The First name has special character or numbers. \nThis is not allowed.");
            document.getElementById("subscriberName").focus(); return false; } }
            document.getElementById("subscriberForm").submit(); }

1 个答案:

答案 0 :(得分:0)

更新按钮的onclick。将return添加为onclick="javascript: return validateForm();"

您按钮的html应该如下。

<button name="button" class="button" id="button" onclick="javascript: return validateForm();" value="Update"> <span style="color:#FFFFFF; font-size: 15px">Add </span> </button> 

您可以在下面对其进行测试。

function validateForm() { 
  return false;
}
function validateFormTrue() { 
  return true;
}
<form name="subscriberForm" modelAttribute="subscriberRequest" method="post" action="/subscriber/saveAjaxSubscriber.htm" id="subscriberForm">
  <button name="button" class="button" id="button" onclick="javascript: return validateForm();" value="Update"> <span style="color:#FFFFFF; font-size: 15px">return false test </span> </button>      
  <button name="button" class="button" id="button" onclick="javascript: return validateFormTrue();" value="Update"> <span style="color:#FFFFFF; font-size: 15px">return true test </span> </button>
</form>