jQuery、表单验证、.each 字段验证后的消息

发布于 2025-01-07 02:48:59 字数 5421 浏览 0 评论 0原文

编辑最终:天哪,我终于发现出了什么问题!我几乎不敢相信,我正在不间断地测试这件作品8个小时,最后……我仍然不确定什么、如何以及为什么,但似乎出于某种原因(我认为)我不能重新变量有不同的值,因为有不同的字段,一次是文本,另一次是数字,例如,如果我只是为每个可能的正则表达式定义不同的变量而不是重新定义它,那么没问题! oO

我已经在这篇文章下的回复中发布了我现在使用的代码,

非常感谢任何花时间阅读和思考这个问题的人!

如果有人知道为什么会出错,我非常感兴趣!


原始问题:

无法找到为什么这不起作用的逻辑..我有一个要验证的表单,每个字段都应该在Blur上验证:工作完美,提交时应该验证每个字段:工作完美,当有某种错误,它应该显示一条消息并返回 false:不起作用..出于某种原因,提交函数只是不想在 .each 之后执行任何操作,当我不对错误进行任何检查时它甚至不会工作,并且只是想要在之后收到警报.each..

编辑:在提到一些小错误之后,不幸的是它仍然无法工作..这是总代码,包括checkfield函数(错误消息是荷兰语的,以防万一您想知道;))

编辑2 :经过更多测试,似乎不是因为 checkform 函数,而是与正则表达式测试( if (!re.test(fieldvalue)) )有关,导致代码卡住.. 但找不到问题.. 任何想法将不胜感激!

EDIT3:为什么带有正则表达式的 checkfield 函数不会与 .each 循环?有人吗??我真的很绝望..-.-

function trim(str){
  return str.replace(/^\s+|\s+$/g, '');
}

function checkfield(field){  

  var output = 'validate' + $(field).attr("name");
  var type = $(field).attr("type");
  if ($(field).hasClass('required')){var required = 1;}

  //set patterns for different types
  if (type == 'text') { var re = /^[A-Za-z0-9 -._]+$/;} 
  if (type == 'number') { var re = /^[\d -.]+$/;} 
  if (type == 'email') { var re = /^[\w-_.]+@[\w]+\.[\w]*\w\w$/;} 
  if (type == 'date') { var re = /^[0-3][0-9][\/-][0-1][0-9][\/-](19|20)[0-9][0-9]$/;} 

  var fieldvalue = trim(field.value); //trim value of input

  if (required == 1 && emptyString.test(fieldvalue)) { //is required field filled in? if no, return false
     $('#'+output).html('Invullen van onderstaand veld is verplicht!');

     field.focus();
     return false;  
    }

  else if (fieldvalue != "" && type != '' && !re.test(fieldvalue)) { //input according to pattern? if no: place message, return false

     if (type == 'email') {$('#'+output).html('Dit is geen correct e-mailadres!');}
     else if (type == 'date') {$('#'+output).html('Dit is geen correcte datum!');}
     else {$('#'+output).html('U gebruikt tekens die niet zijn toegestaan!');}

     field.focus(); 
     return false;
    }

  else if (fieldvalue != ""){ //when no error and filled in, empty messagebox, return true 
     $('#'+output).html('');

     return true; 
    }

  else if (required == 0 && fieldvalue == ""){//is empty but not required, empty messagebox, return true
     $('#'+output).html('');
     document.getElementById(output).innerHTML = '';
     return true;   
    }
}


$(document).ready(function(){

  $("#userform input").blur(function(){
  checkfield(this);
  })

  $("#userform").submit(function(){
    var errs = 0;
    $("#userform input").each(function(){
      if (!checkfield(this)) errs +=1;
    }); 
    if (errs>0) {alert('one or more fields are not correctly filled in'); return false;}

  })
});

有效的新代码!!

如果有人喜欢使用简单的表单验证,请随意;)(空格不太好,但那是因为我的代码编辑器与此网站有不同的规则..)

function trim(str){
  return str.replace(/^\s+|\s+$/g, '');
}

function checkfield(field){  
  var output = 'validate' + $(field).attr("name");
  var type = $(field).attr("type");

  if ($(field).hasClass('required')){var required = 1;}
  var re_text = /^[A-Za-z0-9 -._]+$/;   
  var re_number = /^[\d -.]+$/; 
  var re_email = /^[\w-_.]+@[\w]+\.[\w]*\w\w$/; 
  var re_date = /^[0-3][0-9][\/-][0-1][0-9][\/-](19|20)[0-9][0-9]$/;    
  var emptyString = /^\s*$/ ;

  var error = 0;

  var fieldvalue = trim(field.value); //trim value of input

if (required == 1 && emptyString.test(fieldvalue)) { //is required field filled in? if no, return false
   $('#'+output).html('Invullen van onderstaand veld is verplicht!');
     field.focus();
     return false;  
}

else if (!emptyString.test(fieldvalue)){
 if (type == 'text'){    
   if (!re_text.test(fieldvalue)) {       
     $('#'+output).html('U gebruikt tekens die niet zijn toegestaan!'); 
         error = 1;          
     field.focus();  
       return false;         
   }
     else {$('#'+output).html(''); return true; }    
 }

 if (type == 'number'){  
   if (!re_number.test(fieldvalue)) {     
     $('#'+output).html('U gebruikt tekens die niet zijn toegestaan!');              
     error = 1;
         field.focus();  
       return false;         
   }    
     else {$('#'+output).html(''); return true; }    
 }

 if (type == 'email'){   
   if (!re_email.test(fieldvalue)) {      
     $('#'+output).html('Dit is geen correct e-mailadres!');                 
     error = 1;
         field.focus();  
       return false;         
   }    
     else {$('#'+output).html(''); return true; }    
 }

 if (type == 'date'){    
   if (!re_date.test(fieldvalue)) {       
     $('#'+output).html('Dit is geen correcte datum!');              
     error = 1;
         field.focus();  
       return false;         
   }    
     else {$('#'+output).html(''); return true; }    
 }  
}     

else if (required == 0 && emptyString.test(fieldvalue)){//is empty but not required, empty messagebox, return true
 $('#'+output).html('');
     document.getElementById(output).innerHTML = '';
     return true;   
}

}


$(document).ready(function(){

$("#userform input").blur(function(){
checkfield(this);
})

  $("#userform").submit(function(){
var errs = 0;


$("#userform .form").each(function(){
  if (!checkfield(this)) errs +=1;
        //checkfield(this);
}); 
if (errs>0) {alert('one or more fields are not correctly filled in'); return false;}
//alert(errs); return false;

})
}); 

EDIT FINAL: OMG, i finally found out what goes wrong!! i allmost can't believe, i am testing this piece for 8 hours non stop, and finally...... i am still not sure what and how and why, but it appears that for some reason (i think) i cant have different values for the re-variable, because there are different fields, 1 time, its for a text and the other time for a number, for example, if i just define different variables for each possible regex in stead of redefining it, there is no problem! o.O

i have posted the code that i use now in a reply under this post

thanks so much for anyone that have spend some time reading and thinking about this!!

if anyone has ideas on why it went wrong, i am very interested!


original question:

cant find the logic why this wont work.. i have a form that i want to validate, each field should be validated onBlur: works perfect, on submit it should validate each field: works perfect, when there is some kind of error, it should show a message and return false: does not work.. for some reason, the submit function just does not want to do anything after the .each, it wont even work when i dont do any check on errors, and just want an alert after the .each..

EDIT: after the mentions of some little errors, it unfortunately still wont work.. here is the total code, inclusive the checkfield-function (the error messages are in dutch, in case you're wondering ;))

EDIT2: after more testing, it seems its not because of the checkform function, but something to do with the regex test ( if (!re.test(fieldvalue)) ) that gets the code stuck.. cant find the problem though.. any thoughts would be much appreciated!

EDIT3: why wont the checkfieldfunction with the regex not loop with .each?? anyone?? i am really desperate.. -.-

function trim(str){
  return str.replace(/^\s+|\s+$/g, '');
}

function checkfield(field){  

  var output = 'validate' + $(field).attr("name");
  var type = $(field).attr("type");
  if ($(field).hasClass('required')){var required = 1;}

  //set patterns for different types
  if (type == 'text') { var re = /^[A-Za-z0-9 -._]+$/;} 
  if (type == 'number') { var re = /^[\d -.]+$/;} 
  if (type == 'email') { var re = /^[\w-_.]+@[\w]+\.[\w]*\w\w$/;} 
  if (type == 'date') { var re = /^[0-3][0-9][\/-][0-1][0-9][\/-](19|20)[0-9][0-9]$/;} 

  var fieldvalue = trim(field.value); //trim value of input

  if (required == 1 && emptyString.test(fieldvalue)) { //is required field filled in? if no, return false
     $('#'+output).html('Invullen van onderstaand veld is verplicht!');

     field.focus();
     return false;  
    }

  else if (fieldvalue != "" && type != '' && !re.test(fieldvalue)) { //input according to pattern? if no: place message, return false

     if (type == 'email') {$('#'+output).html('Dit is geen correct e-mailadres!');}
     else if (type == 'date') {$('#'+output).html('Dit is geen correcte datum!');}
     else {$('#'+output).html('U gebruikt tekens die niet zijn toegestaan!');}

     field.focus(); 
     return false;
    }

  else if (fieldvalue != ""){ //when no error and filled in, empty messagebox, return true 
     $('#'+output).html('');

     return true; 
    }

  else if (required == 0 && fieldvalue == ""){//is empty but not required, empty messagebox, return true
     $('#'+output).html('');
     document.getElementById(output).innerHTML = '';
     return true;   
    }
}


$(document).ready(function(){

  $("#userform input").blur(function(){
  checkfield(this);
  })

  $("#userform").submit(function(){
    var errs = 0;
    $("#userform input").each(function(){
      if (!checkfield(this)) errs +=1;
    }); 
    if (errs>0) {alert('one or more fields are not correctly filled in'); return false;}

  })
});

new code that works!!

if anyone likes to use a simple form validation, feel free ;) (the spaces are not exactly nice, but thats beacuse my code editor has different rules than this website..)

function trim(str){
  return str.replace(/^\s+|\s+$/g, '');
}

function checkfield(field){  
  var output = 'validate' + $(field).attr("name");
  var type = $(field).attr("type");

  if ($(field).hasClass('required')){var required = 1;}
  var re_text = /^[A-Za-z0-9 -._]+$/;   
  var re_number = /^[\d -.]+$/; 
  var re_email = /^[\w-_.]+@[\w]+\.[\w]*\w\w$/; 
  var re_date = /^[0-3][0-9][\/-][0-1][0-9][\/-](19|20)[0-9][0-9]$/;    
  var emptyString = /^\s*$/ ;

  var error = 0;

  var fieldvalue = trim(field.value); //trim value of input

if (required == 1 && emptyString.test(fieldvalue)) { //is required field filled in? if no, return false
   $('#'+output).html('Invullen van onderstaand veld is verplicht!');
     field.focus();
     return false;  
}

else if (!emptyString.test(fieldvalue)){
 if (type == 'text'){    
   if (!re_text.test(fieldvalue)) {       
     $('#'+output).html('U gebruikt tekens die niet zijn toegestaan!'); 
         error = 1;          
     field.focus();  
       return false;         
   }
     else {$('#'+output).html(''); return true; }    
 }

 if (type == 'number'){  
   if (!re_number.test(fieldvalue)) {     
     $('#'+output).html('U gebruikt tekens die niet zijn toegestaan!');              
     error = 1;
         field.focus();  
       return false;         
   }    
     else {$('#'+output).html(''); return true; }    
 }

 if (type == 'email'){   
   if (!re_email.test(fieldvalue)) {      
     $('#'+output).html('Dit is geen correct e-mailadres!');                 
     error = 1;
         field.focus();  
       return false;         
   }    
     else {$('#'+output).html(''); return true; }    
 }

 if (type == 'date'){    
   if (!re_date.test(fieldvalue)) {       
     $('#'+output).html('Dit is geen correcte datum!');              
     error = 1;
         field.focus();  
       return false;         
   }    
     else {$('#'+output).html(''); return true; }    
 }  
}     

else if (required == 0 && emptyString.test(fieldvalue)){//is empty but not required, empty messagebox, return true
 $('#'+output).html('');
     document.getElementById(output).innerHTML = '';
     return true;   
}

}


$(document).ready(function(){

$("#userform input").blur(function(){
checkfield(this);
})

  $("#userform").submit(function(){
var errs = 0;


$("#userform .form").each(function(){
  if (!checkfield(this)) errs +=1;
        //checkfield(this);
}); 
if (errs>0) {alert('one or more fields are not correctly filled in'); return false;}
//alert(errs); return false;

})
}); 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

红ご颜醉 2025-01-14 02:48:59

看起来您需要在 .each() 中切换 + 和 =

if (!checkfield(this)) errs += 1;

Looks like you need to switch around the + and = in your .each()

if (!checkfield(this)) errs += 1;
就是爱搞怪 2025-01-14 02:48:59

正如 Brad Falk 指出的那样,您应该使用 errs += 1 而不是 errs =+1。但是,还存在一些其他错误。

您在 .each() 调用后缺少一个分号。这是我看到的唯一可能导致您出现问题的事情。

除此之外,您的 return false 不是 if 语句块的一部分,因此即使没有验证错误,它也始终会阻止表单提交 - 这可能是你想要什么,但由于我看不到任何 AJAX 帖子的证据,可能会在将来给你带来问题。

As Brad Falk pointed out, you should be using errs += 1 rather than errs =+1. However, there are a few other errors as well.

You're missing a semi-colon after the .each() call. This is the only thing I can see that may cause your problem.

In addition to that, your return false isn't part of the if statement block, so it will always prevent form submission even when there are no validation errors - this may be what you want, but since I can't see any evidence of an AJAX post instead, may cause you problems in the future.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文