-1

在 php 项目上工作只想在注册表的所有字段中一次进行验证。

  • 字段
  • 姓名
  • 地址
  • 移动的

以上所有字段都是必需的,所以我可以只写一个验证函数吗

function validateForm()
{
   if (document.myForm.name.value == "")
   {
      alert("Please enter the name");
      document.myForm.name.focus();
      return false;
   }
   if (document.myForm.address.value == "")
   {
      alert("Please enter the address");
      document.myForm.address.focus();
      return false;
   }
...
}

而不是这个我怎么能只写一个函数代码,这样我就不需要单独检查所有的文本框值。

4

1 回答 1

0

如果将 ID 添加到输入字段...

<input type="text" name="name" id="name"/>
<input type="text" name="address" id="address"/>
<input type="text" name="mobile" id="mobile"/>

然后你可以做类似的事情......

var Fields = [['name', 'your name'],
              ['mobile', 'your mobile number'],
              ['address', 'your address']]

for(x=0; x<Fields.length; x++) {
    if(document.getElementById(Field[x][0]).value == '') {
        alert('Please enter ' + Field[x][1]);
        return false;
    }
}
于 2013-09-22T11:20:13.670 回答