2016-11-09 106 views
0

我想驗證我的表單,因爲如果它已經存在列表中,我不能在代碼中輸入代碼。使用jQuery驗證驗證自定義方法

<input id="form:inptCode" type="text" name="form:inptCode" class="number"> 

Bellow是primefaces orderlist元素的html。

<select id="form:choices_values" name="form:choices_values" multiple="true" class="ui-helper-hidden"> 
    <option value="1" selected="selected">1</option> 
</select> 

因此,該列表包含值1.如果我在inputText中鍵入數字1,應該出現錯誤消息。

爲了達到這個目的,我添加了一個方法,並且當這個方法返回false時我嘗試驗證窗體。 我沒有太多使用jQuery驗證的經驗,實際上我只寫了幾個方法。

$.validator.addMethod('codExistss', function (value, element) { 
    var lstChoices = document.getElementById('form:choices_values'); 
    for (i = 0; i &lt; lstChoices.options.length; i++) { 
     return value === lstChoices.option[i].value; 
    } 
}, "The code already exists."); 

$(document).ready(function() { 
    $('#form').validate({ 
    rules: { 
     'form:inptCode': { 
       codExistss: false 
     } 
    } 
    }); 
}); 

看來我的代碼不起作用。那麼,你能幫我理解爲什麼嗎?

+0

更改 「<」 來<。 –

+0

我剛剛在這裏寫了錯誤的名稱,但在我的頁面中它是正確的,並且該方法不起作用。 –

+0

你有任何控制檯錯誤? –

回答

0

你必須在所有選項列表中一個循環:

for (i = 0; i &lt; lstChoices.options.length; i++) { 
     return value === lstChoices.option[i].value; 
    } 

假設你將有超過1個選擇,這是不夠的,只有1次的條件將返回true,你的驗證是毀了。

第二個東西,你不打開你的自定義函數的規則標誌: 你有codExistss: false這意味着「不要被這條規則驗證輸入」,將其更改爲true。

試試這個:

$.validator.addMethod('codExistss', function (value, element) { 

     var lstChoices = document.getElementById('form:choices_values'); 
     if(lstChoices.options[lstChoices.selectedIndex].value===value) {return false;} 
     return true; 
     },"The code already exists."); 

$(document).ready(function() { 
    $('#form').validate({ 
    rules: { 
     'form:inptCode': { 
    // Specify that form:inptCodeshould be validated 
    // by codExistss rule 
       codExistss: true 
     } 
    } 
    }); 
}); 
+0

只有當方法返回false時,我的字段才應該有效。如果我指定codExistss:true當codExistss返回false時,它如何驗證? –

+1

不,您的字段僅在函數返回TRUE時有效,否則返回FALSE無效。 –

+0

@NellyJunior,從它看起來如何,你想從選擇下拉列表中選擇的值進行比較,我編輯了代碼,看一看。 –