验证时,所有文本输入均为空白

时间:2012-12-20 00:26:25

标签: javascript jquery

我的问题是,如果每个问题有任何空白文本输入,我怎样才能显示验证消息?

这是一个小提琴,所以你可以测试它:http://jsfiddle.net/cbyJD/87/

下面是validation()函数代码:

function validation() {

    // only keeping track of the final message
    var alertValidation = "",
        // toggle for showing only one error
        showOnlyOneError = true;

    $("input[data-type='qmark']").each(function(i) {  
        var questions = $(this).attr("data-qnum");
        var marks = parseInt($("[class*=q" + (i+1) + "_ans_text]").text()); 
        var txtinput = $(this).val(); 

        // the message for this question
        var msg = '';

        if (txtinput == '') {
            msg += "\n\u2022 You have not entered in a value in all the Indivdiaul Marks textbox \n";
        }

        if (marks < 0) {
            msg += "\n\u2022 Your Total Marks Remaining does not equal 0 \n - You Need To Remove " + Math.abs(marks) +  " Marks";   
        } else if (marks > 0) {
            msg += "\n\u2022 Your Total Marks Remaining does not equal 0 \n - You Have " + marks +  " Marks Remaining";   
        }

        // if there is an error for the question, add it to the main message
        if (msg.length) {
            alertValidation += alertValidation.length ? '\n\n' : '';
            alertValidation += "You have errors on Question Number: " + questions + "\n";
            alertValidation += msg;
            // stop if we only care about the first error
            return !showOnlyOneError;
        }
    });

    // show the error messages
    if (alertValidation != "") {
        alert(alertValidation);
        return false;
    }

    return true;
}

1 个答案:

答案 0 :(得分:0)

这是你的“第一次错误后的回归”。如果你填写第一个框但它有其他错误,你将只得到那些错误 - 第二个框没有被检查,你永远不会发现它是空的。最明显的修复是showOnlyOneError = false

如果这不是您想要的,那么您必须更详细地解释showOnlyOneError所需的语义。

(另外,提示:将错误推入数组然后将其与"\n\n"连接起来比每次检查消息字符串是否为空都要轻松得多。)