我想建立一個定製的客戶端jQuery驗證,並試圖忽略,我從HTML5數據生成的默認值屬性與HTML 5的數據屬性和默認值jQuery的自定義驗證
$('input, textarea').each(function() {
if ($(this).data('val-default')) {
$(this).focus(function() {
if (this.value == $(this).data('val-default'))
this.value = '';
});
$(this).blur(function() {
if (this.value == '')
this.value = $(this).data('val-default');
});
this.value = $(this).data('val-default');
}
});
因此,與上面的代碼我可以添加默認值輸入和textarea元素這樣
data-val-default="Type your first name here"
佔位符屬性是不幸的不是一個選項尚未
問題沒有w是該我試圖驗證具有jQuery驗證這些元件這樣
$.validator.addMethod("ignoreDefaultValues", function (value, element) { if ($(element).data('val-default')) return !($(element).data('val-default') == element.value); return true; }, "Required field" );
$('form#contact-form').submit(function (e) {
e.preventDefault();
if (!$(this).valid({
rules:
{
title:
{
ignoreDefaultValues: true,
required: true
},
description:
{
ignoreDefaultValues: true,
required: true
},
name:
{
ignoreDefaultValues: true,
required: true
},
email:
{
ignoreDefaultValues: true,
required: true
}
}
})) {
alert("NOT VALID!");
}
else
{
alert("IS VALID!");
//todo: ajax post to server
}
});
下面是一個輸入元件的一例
<input type="text" class="firstname" name="firstname" data-val-default="Type your first name here" data-val="true" data-val-required="*" />
的jQuery驗證似乎忽略規則。如果我測試例如通過鍵入一個空的空間它將驗證並提醒「無效」,但它只是忽略我的自定義驗證。
我在做什麼錯了?
我錯過了什麼嗎?