我試圖驗證一個窗體,它既有隱藏的輸入,也有隱藏的輸入。我在表單驗證設置中添加了行ignore:「」來驗證隱藏的輸入,但是這樣做並不驗證在它之前的所需文本輸入,但僅在其後面進行。 發生的另一件事是,名字的驗證在第一次提交後模糊處理(但它不會阻止提交本身)。jquery驗證插件:驗證隱藏的輸入,跳過所需的輸入文本
這裏是我的代碼,並鏈接到js小提琴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>
什麼是'countryCode'驗證邏輯?只有在指定了「country」時才需要這樣做? – 2013-02-23 15:46:19
是的,因爲我需要驗證從自動完成中選擇了有效的國家/地區。這樣我就可以驗證國家是否填充了,並選擇了countryCode(國家代碼是需要服務器端的)。 – Rohi 2013-02-23 15:52:25
你可以檢查http://jsfiddle.net/arunpjohny/68uu5/3/,看看你的要求是否符合 – 2013-02-23 15:54:11