找回密码
 注册
搜索
热搜: 回贴

JavaScript验证整个表单

2009-12-16 23:48| 发布者: admin| 查看: 115| 评论: 0|原作者: 九天玄女

不像域级有效性检查(field-level validation),表单级有效性检查(form-level validation)将整个表单上的某组(或全部)值作为一个整体分析其一致性。表单级有效性检查一般发生在将一个已完成的HTML 表单提交给CGI 程序之前。我们这样做是为了确保用户在将数据发送至服务器之前,已经填写了所有的必填域。
情缘.教程_网 [http://Www.XiuGoo.Com]
验证整个表单其实相当简单。在我们的例子当中,我们已经去除了大部份会自动弹出即时警告信息的域级有效性检查。下面是一个例子:
function isANumber(number) {
answer = 1;
if (!parseFloat(number)) {
//the first digit wasn't numeric
answer = 0;
} else {
//the first digit was numeric, so check the rest
for (vari=0; i if ((number.charAt(i) != "0")
&& (!parseFloat(number.charAt(i)))) {
answer = 0;
break;
}
}
}
if (answer == 1) {
orderPlaced = true;
}
return answer;
}
上面的代码,基本上是我们前面的数字检查函数,只不过没有JavaScript 警告信息。在这个情况中,如果用户输入了数字以外的字符,我们不会自动发送错误信息。
一旦用户认为她已经完成了整个表单,那么她就可以按下 Submit(提交)按钮。在那个时候,我们就检查每个域是否有遗漏,或是存有格式不正确的数据。
function validateForm() {
varfixThis = "";
if
(!(isANumber(document.orderForm.numberOrdered.value))) {
fixThis += "Please enter a numeric value
for the number of brains field.\n";
}
if
(!(exists(document.orderForm.typeField.value))) {
fixThis += "Please enter the type.\n";
}
if
(!(exists(document.orderForm.stateField.value))) {
fixThis += "Please enter the state.\n";
}
if
(!(isAPhoneNumber(document.orderForm.phoneNumber.value))) {
fixThis += "Please enter the phone number
in the following format: (123)456-7890";
}
if
(fixThis != "") {
alert(fixThis);
} else {
document.location.href = "thanks.html";
}
}
这个函数检查表单中所有的域,以确保每个域都包含有效的值。倘若它发现某个域缺少有效的数据,它就会在fixThis变量添加一个新的警告信息,然后再继续下去。在最后,它要么弹出一个含有各种警告信息的窗口,就是传送一个简短的“Thank You”给用户。
注意:这个例子检查了表单中我们没有提到的一部分——State 框,它根据用户输入的美国各州的编码计算销售所得税。

最新评论

QQ|小黑屋|最新主题|手机版|微赢网络技术论坛 ( 苏ICP备08020429号 )

GMT+8, 2024-9-29 13:29 , Processed in 0.089788 second(s), 12 queries , Gzip On, MemCache On.

Powered by Discuz! X3.5

© 2001-2023 Discuz! Team.

返回顶部