js验证中的错误在哪里

时间:2014-11-07 00:22:14

标签: javascript

我现在正在进行表单验证。当有错误时,Onsubmit是sumbmitting。我不确定问题出在哪里。我认为它围绕代码的正则表达式部分,但不确定。这个验证脚本中的错误在哪里?

function test_form()
{

  var userName = document.regForm.userName.value;
  var firstName = document.regForm.firstName.value;
  var lastName = document.regForm.lastName.value;
  var email = document.regForm.email.value;
  var email2 = document.regForm.email2.value;
  var password = document.regForm.password.value;
  var password2 = document.regForm.password2.value;
  var birthDay = document.regForm.birthDay.value;
  var birthMonth = document.regForm.birthMonth.value;
  var birthYear = document.regForm.birthYear.value;
  var tou = document.regForm.tou.checked;

  var regSpec = /!|@|#|\$|%|-|_|&|\*|\(|\)|\+|\[|\]|\{|\}|:|;|'|"|\||\\|,|<|>|\.|\?|\/|\^/;
  var regUser = /!|@|#|\$|%|&|\*|\(|\)|\+|\[|\]|\{|\}|:|;|'|"|\||\\|,|<|>|\.|\?|\/|\^/;

  var error = false;

  // Test all fields for empty and dob format and tou acceptance

 if(userName === "" || firstName === "" || lastName === "" || email === "" || email2 ===    ""     || password === "" || password2 === "" || tou == false || birthDay == "--Day--" ||         birthYear == "--Year--" || birthMonth == "--Month--")
 {

   error = true;

 }

  // Test all fields for applicable special characters

 if(firstName.match(regSpec) || lastName.match(regSpec))
 {

  error = true;

 }


 if(userName.match(regUser) || password.match(regUser) || password2.match(regUser))
 {

  error = true;

 }

 // Test emails for format and match

 if(email.indexOf("@") == -1 || email.indexOf(".") == -1 || email2.indexOf("@") == -1 ||      email2.indexOf(".") == -1)
  {

   error = true;

  }

 // Test passwords for match

 if(password != password2)
 {

  error = true;

 }

  // test email for match

 if(email != email2)
 {

  error = true;

 }

 // Send

 return error;


} 

1 个答案:

答案 0 :(得分:0)

你是如何使用这个功能的?要停止提交表单,您必须返回false。如果此函数用作onsubmit处理程序,那么如果有错误,该函数返回true,这意味着表单将提交 - OJay 16分钟前

这位意见提供者是对的。我将布尔值更改为noError,并确保将错误设置为false。现在很棒。只需要做一些PHP验证:)谢谢。