表单验证不检查表达式

时间:2013-10-10 00:53:09

标签: javascript

这是我的代码,我无法弄清楚它在哪里坏了。它的运行方式就好像它从不检查变量是否写入正确的正则表达式。任何帮助搞清楚我出错的地方都会非常感激。

<script>

function allNumbers( field, msg ) {
var numberexp = /^[0-9]+$/;
if ( field.value.match( numberexp ) ) {
   return true;
} else {
   alert( msg );
   field.focus();
   return false;
}
}

function allLetters( field, msg ) {
var letexp = /^[a-zA-Z]+$/;
if ( field.value.match( letexp ) ) {
   return true;
} else {
   alert( Msg );
   field.focus();
   return false;
}
}

function notEmpty( field, msg ) {
if ( field.value.length == 0 ) {
   alert( msg );
   field.focus();
   return false;
}
return true;
}

function validateForm() {
    var a = document.getElementById('firstname');
    var b = document.forms["contactrecord"]["lastname"].value;
    var c = document.forms["contactrecord"]["phone"].value;
    var d = document.forms["contactrecord"]["address"].value;
    var e = document.forms["contactrecord"]["city"].value;
    var f = document.forms["contactrecord"]["state"].value;
    var g = document.forms["contactrecord"]["zip"].value;

   if ( allLetters( a, "Incorrect First Name" ) ) {
     if ( allLetters( b, "Incorrect Last Name" ) ) {
       if ( allNumbers( c, "Incorrect Phone Number" ) ) {
         if ( notEmpty( d, "Incorrect address" ) ) {
           if ( allLetters( e, "Incorrect City Name" ) ) {
             if ( allNumbers( g, "Incorrect Zip Code") ) {
                return true;
             }
           }
         }
       }
     }
   }
   return false;
}

</script>

2 个答案:

答案 0 :(得分:0)

我猜您在name中缺少input个属性。把它们放在那里。

答案 1 :(得分:0)

我不是这样做的,但这是你的代码。您传递了每个表单控件的值,而函数期望引用表单控件。

请注意,该函数现在需要对表单的引用,因此您可以执行以下操作:

<form onsubmit="validateForm(this);" ...>


function allNumbers(field, msg) {

  // If has a non-number character, return false
  if (/\D/.test(field.value)) {
    field.focus();
    return false;
  }
  return true;
}

// If value has a non-word character, return false
function allLetters(field, msg) {
  if (/\W/.test(field.value)) {
    field.focus();
    return false;
  }
  return true;
}

// If value has no characters, return false
function notEmpty(field, msg) {
  if (field.value.length == 0){
    alert(msg);
    field.focus();
    return false;
  }
  return true;
}

function validateForm(form) {
  var a = document.getElementById('firstname');
  var b = form.lastname;
  var c = form.phone;
  var d = form.address;
  var e = form.city;
  var f = form.state;
  var g = form.zip;

  if (allLetters(a, "Incorrect First Name") &&
      allLetters(b, "Incorrect Last Name")  &&
      allNumbers(c, "Incorrect Phone Number") &&
      notEmpty(d, "Incorrect address") &&
      allLetters(e, "Incorrect City Name") &&
      allNumbers(g, "Incorrect Zip Code")
   ) { 
     return true;
   }
   return false;
}