jquery验证插件:验证隐藏的输入,跳过所需的输入文本

时间:2013-02-23 15:41:03

标签: jquery validation jquery-plugins jquery-validate hidden-field

我正在尝试验证一个包含隐藏和非隐藏输入的表单。我在表单验证设置中添加了行忽略:“”以验证隐藏的输入,但这样做,它不会验证它之前所需的文本输入,但只有在它放置之后。 另一件事是,firstname的验证在第一次提交后对模糊起作用(但它仍然不会阻止提交本身)....

这是我的代码,以及指向js fiddle DEMO的链接:

JS:

    var countries = [{label:"Vanuatu", code:"VU"},
        {label:"Ecuador", code:"EC"}];    
    $().ready(function() {
$('#country').autocomplete({
    source : function(request, response) {
        var matcher = new RegExp('^'+$.ui.autocomplete.escapeRegex(request.term), "i");
        response($.grep(countries, function(element, index) {
            return matcher.test(element.label);
        }));
    },
    delay : 0,
    change : function(event, ui) {
        $('#countryCode').val(ui.item ? ui.item.code : '');
    }
});
$("#signupForm").validate({
    ignore: "",
    rules: {
        firstname: {
            required: true
        },
        lastname: {
            required: true
        },
        country: {
            required: true
        },
        countryCode: {
            required: function(element){
                return $("#signupForm").validate().element( "#country" );
            }
        },
        email: {
            required: true,
            email: true
        }
    },  
    messages: {
        firstname: "Please enter your first name",
        lastname: "Please enter your last name",
        country: "Please select a country",
        countryCode: "Please select a valid country",
        email: "Please enter a valid email address"
    },
    submitHandler: function(form) {
        alert("fine!");
    }
});

});
HTML表单:

    <form id="signupForm" method="post" name="" action="">
<p>
        <label for="firstname"></label>
        <input class="inputText" type="text" id="firstname" name="firstname" placeholder="First Name">
    </p>
            <p>
        <label for="country"></label>
        <input class="inputText" type="text" id="country" name="country" placeholder="Country"/>

        <input type="hidden" name="countryCode" id="countryCode" />
    </p>
                <p>
        <label for="lastname"></label>
        <input class="inputText" type="text" id="lastname" name="lastname" placeholder="Last Name">
                    </p>
                    <p>
        <label for="email"></label>
        <input class="inputText" type="text" id="email" name="email" placeholder="Email">
                        </p>
                        <p>
        <input class="submit" type="submit" id="signupButton" value="SUBMIT" />   
                        </p>
    </form> 

1 个答案:

答案 0 :(得分:1)

我认为问题在于countryCode验证

你可以尝试

countryCode: {
    required: function(element){
        return $("#country").val().length > 0;
    }
}

演示:Fiddle