0

请查看此代码,并告诉我为什么即使我的错误确实被触发,我的错误变量仍然尖叫 0。我已经尝试并尝试让它们改变。我只是在这一点上迷路了。

validationError = 0;
$("#step1continue").click(function(){

        var fname = $('#fname');
        if (fname.val() == "") {
            fname.addClass("needsfilled");
            fname.val('Required!');
                       validationError = 1;
        } else {
                  validationError = 0;
        }

        var lname = $('#lname');
        if (lname.val() == "") {
            lname.addClass("needsfilled");
            lname.val('Required!');
                        validationError = 1;
        } else {
                 validationError = 0;
        }

        var company_name = $('#company_name');
        if (company_name.val() == "") {
            company_name.addClass("needsfilled");
            company_name.val('Required!');
                        validationError = 1;
        } else {
                  validationError = 0;
        }

        var email = $('#email');
        if (email.val() == "") {
            email.addClass("needsfilled");
            email.val('Required!');
                       validationError = 1;
        } else {
                  validationError = 0;
        }

         var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
               if (!emailReg.test(email.val())) {
                        email.addClass("needsfilled");
            email.val('Use a real email address!');
                       validationError = 1;
        } else {
                 validationError = 0;
        }

         var phone = $('#phone');
                if (phone.val() == "") {
            phone.addClass("needsfilled");
            phone.val('Required!');
                        validationError = 1;
        } else {
                  validationError = 0;
        }
                if (phone.val().length < 10) {
            phone.addClass("needsfilled");
            phone.val('10 digits minimum');
                        validationError = 1;
        } else {
                 validationError = 0;
        }   

                var phoneregxp = /^[0-9]$/;
                if (phoneregxp.test(phone.val())) {
                        phone.addClass("needsfilled");
            phone.val('Numbers ONLY');
                        validationError = 1;
        } else {
                  validationError = 0;
        }   

      alert(validationError);

});
4

1 回答 1

3

因为您在每次成功检查时不断重置您的validationError?

如果 (say)#fname未填写,则将validationError 设置为1。没关系。但是然后你检查#lname,哎呀......这是一个填写,所以现在validationError再次为0。

为什么不每次出现错误时都增加该值,而不是像疯了一样猛拉一个简单的开/关值

validationError = 0;
if (...) { validationError++ }
if (...) { validationError++ }
if (validationError > 0) {
   alert('You have ' + validationError + ' errors');
}
于 2012-09-21T22:03:05.907 回答