jQuery验证在页面上第二次不起作用

时间:2011-07-01 18:37:18

标签: jquery jquery-validate

我有一个页面,要求用户输入付款详细信息。这包括账单和信用卡/支票账户信息。他们点击此页面的初始时间所有验证规则都正确启动。然后,他们点击底部的继续按钮,将其带到显示他们输入的所有内容的摘要页面,并允许他们提交付款或按下编辑按钮并返回上一页以更新他们想要的任何字段。

但是,在进行编辑时,验证规则都不再有效。

是的,是的,我已经实现了服务器端验证,所以这真的只是锦上添花,但它使用户体验更好,因为它不会让他们等待回发...

我正在使用jQuery 1.4.4和验证插件1.8.1。有很多验证规则,所以我把它们分成了自己的.js文件,这个文件在我的html中引用

我已经从我的验证器js文件中附加了代码,请记住这些所有工作的初始时间,只有在重新访问之后(使用VB.Net中的Response.Redirect返回页面)他们是否会停止工作..使用Firebug进行调试时,我第二次无法在$(document).ready()块内放置任何断点。

// JScript File

$.validator.addMethod('postalCode', function (value, element) { 
    return this.optional(element) || /^((\d{5}-\d{4})|(\d{5})|([A-Z]\d[A-Z]\s\d[A-    Z]\d))$/.test(value);
}, 'Please enter a valid US or Canadian postal code.');

$.validator.addMethod('cvnnum', function (value, element) { 
    return this.optional(element) || /^((\d{3})|(\d{4}))$/.test(value);
}, 'Please enter a valid CVN.');

$.validator.addMethod('CCExp', function(value, element, params) {
      var minMonth = new Date().getMonth() + 1;
      var minYear = new Date().getFullYear();
      var month = parseInt($(params.month).val(), 10);
      var year = parseInt($(params.year).val(), 10);
      return this.optional(element) || ((year > minYear || (year === minYear && month >= minMonth)));
}, 'Please select a valid expiration date.');

$.validator.addMethod('routingnum', function (value, element) {
      // algorithm taken from: http://www.brainjar.com/js/validation/

    var t = value;
    n = 0;
    for (i = 0; i < t.length; i += 3) {
        n += parseInt(t.charAt(i), 10) * 3
          + parseInt(t.charAt(i + 1), 10) * 7
          + parseInt(t.charAt(i + 2), 10);
    }

    // If the resulting sum is an even multiple of ten (but not zero),
    // the aba routing number is good.

    if (n != 0 && n % 10 == 0)
        return true;
    else
        return (this.optional(element) || false);

}, 'Please enter a valid routing number.');


$.validator.addMethod("phoneUS", function(phone_number, element) {
    phone_number = phone_number.replace(/\s+/g, ""); 
    return this.optional(element) || phone_number.length > 9 &&
        phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");

//had to rewrite equalTo as it didn't follow the required or depends properties correctly..
$.validator.addMethod("myEqualTo", function (value, element, param) {
    return this.optional(element) || value === $(param).val();
}, jQuery.format("You must enter {0}"));


$(document).ready(function () {

$("#form1").validate({
    rules: {
        PayType: { required: true },
        Email: { required: true },
        txtCCFullName: { required: isCreditCard },
        txtCCFName: { required: isCreditCard },
        txtCCLName: { required: isCreditCard },
        txtCCNumber: { creditcard: true, required: isCreditCard },
        txtCCSecurityNum: { cvnnum: true, required: isCreditCard },
        ddlCCExpYear: {
            required: isCreditCard,
            CCExp: {
                month: '#ddlCCExpMonth',
                year: '#ddlCCExpYear'
            }
        },
        txtCCAdd1: { required: isCreditCard },
        txtCCCity: { required: isCreditCard },
        txtCCState: { required: isCreditCard },
        txtCCZip: { postalCode: true, required: isCreditCard },
        txtAmtOther: {
            number: true,
            required: function () { return $('input[name=PayType][value=rbtAmtOther]:checked').length > 0; }
        },
        txtACHRoutingNum: { routingnum: true, required: isACH },
        txtACHAcctNum: { number: true, required: isACH },
        txtACHFName: { required: isACH },
        txtACHLName: { required: isACH },
        txtACHAdd1: { required: isACH },
        txtACHCity: { required: isACH },
        txtACHState: { required: isACH },
        txtACHZip: { postalCode: true, required: isACH },
        txtPayorEmail: {
            email: true,
            required: {
                depends: function (element) { return $('input[id=rbtEmailYes]:checked').length > 0; }
            }

        },
        txtConfEmail: {
            myEqualTo: '#txtPayorEmail',
            //required: false
            required: {
                depends: function (element) {
                    return ($('div[id=ConfirmEmail]:visible').length > 0) && ($('input[id=rbtEmailYes]:checked').length > 0); 
                }
            }
        }

    },
    messages: {
        Email: { required: 'Please answer the payor email question.' },
        PayType: { required: 'Please select a payment type.' },
        // blank messages suppress the individual error messages
        txtCCFullName: { required: '' },
        txtCCFName: { required: '' },
        txtCCLName: { required: '' },
        txtCCNumber: { required: '' },
        txtCCSecurityNum: { required: '' },
        txtAmtOther: { required: '' },
        txtACHFName: { required: '' },
        txtACHLName: { required: '' },
        txtACHRoutingNum: { required: '' },
        txtACHAcctNum: { required: '' },
        txtACHAdd1: { required: '' },
        txtACHCity: { required: '' },
        txtACHState: { required: '' },
        txtACHZip: { required: '' },
        txtCCAdd1: { required: '' },
        txtCCCity: { required: '' },
        txtCCState: { required: '' },
        txtCCZip: { required: '' },
        txtPayorEmail: { required: '' },
        txtConfEmail: { required: '', myEqualTo: 'The email addresses do not match.' }

    },
    onfocusout: function (element) {
        // if either of the email fields, immediately validate, otherwise let the normal behavior happen
        switch ($(element).attr('id')) {
            // validate these on focus lost   
            case 'txtPayorEmail':
            case 'txtConfEmail':
            case 'txtCCNumber':
            case 'txtCCSecurityNum':
            case 'txtCCZip':
            case 'txtACHRoutingNum':
            case 'txtACHAcctNum':
            case 'txtACHZip':
                $(element).valid();
                break;
            default:
                $(element).valid();
                // do nothing for the others, they get validated on form submit
                break;
        }
    },
    errorLabelContainer: $("#form1 div.error"),
    ignore: ":hidden",
    onkeyup: false
    //,debug:true
});

});

function isCreditCard() {
  return $('input[name=PayType][value=rbtCC]:checked').length > 0;
}
function isACH() {
  return $('input[name=PayType][value=rbtACH]:checked').length > 0;
}
function isEmailed() {
    return $('input[id=rbtEmailYes]:checked').length > 0;
}

更新:我现在已经在两个浏览器中尝试了这一点,包括Firefox和Chrome,并且在两者中,验证在页面上第二次不再有效。所以它似乎不是一个特定于FF的bug,而是标准化的东西,我搞砸了......

更新#2:发生在Opera&amp; IE 8也是如此,所以这是第3和第3版。第四个浏览器现在表现得这样。这绝对是我设计的一个基本问题..

在我们的测试和生产网站上,这些网站都在https下运行,但是在本地开发它只是http,在两种情况下都会出现问题。

我在编辑时尝试使用CTRL-F5刷新页面,但仍然存在相同的行为。

我已经检查了第1次和第2次的Live HTTP标头,并且文件的访问方式没有明显的差异。所有js文件都被加载,服务器响应HTTP / 1.1 200 OK's。

我的javascript文件在@Cos Callis提供的链接中被引用与@Ganztoll相同,虽然他使用PHP而我在.NET中,从根本上我看不出动态生成src目标之间的区别与它保持硬编码是。浏览器应该看到完全相同的结果,并相应地对待它...我想我可以给它一个服务器端包含或其他东西..

非常感谢任何其他帮助或解释。

1 个答案:

答案 0 :(得分:3)

好的,所以我是一个笨蛋,用一双新眼睛重新审视之后我发现我在一些初始化代码中调用了$('#form1').validate.resetForm(),这些代码只在编辑信息时才被触发。重新处理我的验证程序后,不再依赖它并动态添加/删除规则,这个神秘的问题就消失了。