2012-03-27 23 views
3

我有一個簡單的表單,並希望添加一個自定義的jQuery驗證規則。我希望文本字段(bonuscode)只有少數可能的值。我假設我需要這些值的數組,但不知道多少JavaScript,我不知道我在哪裏錯了。使用數組中的值進行jQuery驗證

jQuery.validator.addMethod("equals", function(value, element, param) { 
    return this.optional(element) || value == param; 
}, jQuery.format("")); 

$(document).ready(function(){ 
    $("#form").validate({ 
     debug: false, 
     rules: { 
      bonuscode: {equals: ["code1", "code2"]} 
     }, 
     messages: { 
      bonuscode: "That's not a Bonus Code!", 
     }, 
    }); 
}); 

回答

1

在javascript數組中有獎金值不是一個好的解決方案。您可以向服務器發出ajax請求並檢查獎金值。這裏是示例代碼。

您可以使用遙控器選項,在驗證插件來檢查bounus

$("#form").validate({ 
    debug: false, 
    rules: { 
    bonuscode: { 
     required: true, 
     remote: { 
     url: "check-bonus.php", 
     type: "post", 
     data: { 
      bonuscode: function() { 
      return $("#bonuscode").val(); 
      } 
     } 
     } 
    } 
    } 
}); 
+0

爲什麼是不好的做法,包括在JavaScript中的值? 你能告訴我什麼check-bonus.php必須看起來像嗎? 非常感謝您的幫助! – dsol828 2012-03-27 03:30:02

+0

現在明白了。我的最終解決方案發布在OP中供其他人蔘考。謝謝。 – dsol828 2012-03-27 04:40:01

+1

@ dsol828:這是一個不好的做法,因爲您的網站的用戶可能只是「查看源代碼」並查看獎勵代碼。 – 2012-03-28 12:52:56

1

假設這實際上是你的使用情況,@jems可能是正確的話,你應該檢查這種事情在服務器端碼。但是,您的自定義規則已經不遠了:

jQuery.validator.addMethod("equals", function(value, element, param) { 
    return this.optional(element) || $.inArray(value, param) >= 0; // <-- Check if the value is in the array. 
}, jQuery.format("")); 

$(document).ready(function() { 
    $("#form").validate({ 
     debug: false, 
     rules: { 
      bonuscode: { 
       equals: ["code1", "code2"] 
      } 
     }, 
     messages: { 
      bonuscode: "That's not a Bonus Code!", 
     }, 
    }); 
}); 

例子:http://jsfiddle.net/AApJx/

+0

'$ .inArray(value,param)> 0'應該是'$ .inArray(value,param)> -1' 請參閱https://api.jquery.com/jQuery.inArray/ – 2014-02-26 17:09:09

+0

@MaffooClock:thanks for更正,更新 – 2014-02-26 17:24:55