JavaScript验证整个表单2008-05-09不像域级有效性检查(field-level validation),表单级有效性检查(form-level validation)将整个表单上的某组(或全部)值作为一个整体分析其一致性。表单级有效性检查一般发生在将一个已完成的Html 表单提交给CGI 程序之前。我们这样做是为了确保用户在将数据发送至之前,已经填写了所有的必填域。验证整个表单其实相当简单。在我们的例子当中,我们已经去除了大部份会自动弹出即时警告信息的域级有效性检查。下面是一个例子:function isANumber(number) {answer = 1;if (!parseFloat(number)) {//the first digit wasn"t numericanswer = 0;} else {//the first digit was numeric, so check the restfor (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 valuefor the number of brains field.
";}if(!(exists(document.orderForm.typeField.value))) {fixThis += "Please enter the type.
";}if(!(exists(document.orderForm.stateField.value))) {fixThis += "Please enter the state.
";}if(!(isAPhoneNumber(document.orderForm.phoneNumber.value))) {fixThis += "Please enter the phone numberin the following format: (123)456-7890";}if(fixThis != "") {alert(fixThis);} else {document.location.href = "thanks.html";}}这个函数检查表单中所有的域,以确保每个域都包含有效的值。倘若它发现某个域缺少有效的数据,它就会在fixThis变量添加一个新的警告信息,然后再继续下去。在最后,它要么弹出一个含有各种警告信息的窗口,就是传送一个简短的“Thank You”给用户。注意:这个例子检查了表单中我们没有提到的一部分——State 框,它根据用户输入的美国各州的编码计算销售所得税。