0

这是我的代码,我不知道它在哪里坏了。它的运行就像它从不检查变量中写入的正确正则表达式一样。任何帮助找出我哪里出错了,我们将不胜感激。

<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>
4

2 回答 2

0

我的猜测是你在你的 s中缺少name属性。input把它们放在那里。

于 2013-10-10T01:09:23.650 回答
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;
}
于 2013-10-10T01:14:35.110 回答