循环以限制验证尝试

loop to limit attempts at validation

本文关键字:验证 循环      更新时间:2023-09-26

我正在尝试找出一种简单的方法来限制通过javascript中的while循环对字段的尝试次数。只是似乎不想循环,但验证仍在工作。这是我尝试使用的代码:

 function validateForm() {
     x=document.forms["Form"]["name"].value;
     var i=0;
     var sum=0;
     do {
         sum += i;
         i++;
     }
     while (i < 3)
     if (x==null || x=="") {
         alert("First name must be filled out");
         return false;
     }
}

提前感谢您的任何想法。

您必须将变量存储在函数之外:

 var numOfTries = 0;
 function validateForm() {
     if(++numOfTries > 3) {
         alert('You have reached the maximum number of tries!');
         location.replace("error_page.html"); // do something about it
     }
     x = document.forms["Form"]["name"].value;
     if (x == null || x == "") {
         alert("First name must be filled out");
         return false;
     }