javascript中的javascript throw语句准备好了吗?

时间:2011-11-02 02:36:31

标签: javascript jquery validation

所以我想知道以下是否合法,或许由于语法错误而无效。在单个搜索字段上简单验证四个规则。感谢您对优雅和启发性解决方案的任何帮助!

 $(function() { 
    $('input.text').focus(function() {
        $(this).removeClass('noSubmitX');
        $('.enterX').removeClass('now').text( orig);
    });  //reset error status

    var orig = "Enter the title you want.";
    var msg1 = "Title must be between 3 and 63 characters.";
    var msg2 = "Title cannot begin or end with a hypen";
    var msg3 = "Title cannot contain a hyphen at character positions 3 and 4";

    $('form.xSearch').submit(function() {
        var theSearch = $('input.text').val();
        var xLong = $('input.text').val().length;
        var firstx = (theSearch[0]);
        var thirdx = (theSearch[2]);
        var fourthx = (theSearch[3]);
        var lastx = (theSearch[xLong - 1]);
        try {
            if (xLong < 2 || xLong > 62) {
                throw "msg1";
            }
            else if (firstx == "-") || (lastx == "-") {
                throw "msg2";
            }
            else if (thirdx == "-") && (fourthx == "-")

            {
                throw "msg3";
            }
        }
        catch (er) {
            if (er == 'msg1') {
                $('input.text').addClass('noSubmitX');
                $('.enterX').addClass('now').text('Title must be between 3 and 63 characters.');
            }
            if (er == 'msg2') {
                $('input.text').addClass('noSubmitX');
                $('.enterX').addClass('now').text('Title cannot begin or end with a hypen');
            }
            if (er == 'msg3') {
                $('input.text').addClass('noSubmitX');
                $('.enterX').addClass('now').text('Title cannot contain a hyphen at character positions 3 and 4');
            }
        }
    });
});

1 个答案:

答案 0 :(得分:4)

我认为您的if声明遇到了麻烦。它们需要用括号括起来或像这样包裹起来:

if (xLong < 2 || xLong > 62) {
    throw "msg1";
}
else if (firstx == "-" || lastx == "-") {
    throw "msg2";
}
else if (thirdx == "-" && fourthx == "-") {
    throw "msg3";
}