[英]Validate select box with own custom message and rule in Jquery validation plugin
[英]Adding own rule in jquery validation plugin
我有下一個jquery代碼:
$("input").rules("add", {
required: true,
messages: {
required: 'Please enter your telephone number'
},
errorPlacement: function(error, element) {
console.log('bob');
element.insertBefore(error);
}
});
我試圖在這個問題中添加新規則,如回答: jquery驗證和id的ft數字
我有這樣的HTML代碼:
<form method='post' action='' id='#countersForm'>
<input id="88" class="counter_input active" type="text" enabled="">
<input id="89" class="counter_input active" type="text" enabled="">
</form>
我的問題是:
1)為什么瀏覽器嘗試驗證加載頁面上的字段? 我不需要這個(在頁面加載時出現消息bob)。
2)為什么只有第一個輸入字段在驗證? 我想驗證所有字段。
3)為什么控制台說,該元素沒有定義?
文檔說元素參數包含驗證元素。 console.log(element)
說它沒有被修改。 為什么?
來自文檔 :
讀取,添加和刪除元素的規則。
它說'一個'元素。 在您的情況下$('input')
返回兩個元素。
驗證插件使用元素的name
屬性,您的元素沒有名稱。
您必須使用要validate()
的form
上的validate()
方法初始化插件,例如
$("#myform").validate({ //where my form is the id of your form
rules: {
name: "required", //name is the name of your element
},
messages: {
}
});
感謝您的回答和評論。
我解決了我的問題。 工作代碼(當前問題已解決)在這里: http : //jsfiddle.net/2LRv7/2/
我的js代碼中存在一個巨大的錯誤。 我把errorPlacement
部分放到規則函數中。 我必須把這個選項放到.validate
部分。
$("#countersForm").validate({
errorPlacement: function (error, element) {
console.log(error);
var br = $( "<br>" );
error.insertAfter(element);
br.insertAfter(element);
}
});
另外,正如@TilwinJoy所說,我用$('input').rules(/*....*/)
錯了。 我不得不使用each
功能。
這段代碼沒問題:
$("input").each(function () { // next code will affect all input fields
$(this).rules("add", { // $(this) is my input field
required: true,
digits: true,
messages: {
required: 'Это поле обязательно для заполнения',
digits: 'В поле могут быть только цифры'
}
});
});
當前問題解決了,但我有另一個問題。 如果你想幫助檢查一下這個問題: 第一次檢查時沒有將類添加到error元素中,但是當再次檢查字段時一切正常(jquery驗證插件)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.