DataAnnotation Range 屬性的客戶端驗證之旅
我的模型類中有以下程式碼:
[Range(1, 100)] public decimal Price { get; set; }在最近將 jquery.validate 升級(我假設)到 1.11.0 之後,即使我輸入了有效值,我也會收到錯誤消息。如果我在 web.config 中關閉客戶端驗證 - 工作正常。所有其他屬性(StringLength,必需)都可以正常工作。生成的 HTML 如下(為清楚起見添加了換行符):
<input class="text-box single-line" data-val="true" data-val-number="The field Price must be a number." data-val-range="The field Price must be between 1 and 100." data-val-range-max="100" data-val-range-min="1" data-val-required="The Price field is required." id="Price" name="Price" type="text" value="" />我很確定它以前工作過……除了 jquery.validate 中的錯誤之外,什麼都想不到。
Microsoft 發布了對 microsoft.jQuery.Unobtrusive.Ajax 和 microsoft.jQuery.Unobtrusive.Validation 的更新(從版本“2.0.20710.0”到“2.0.30116.0”),修復了.live 和驗證問題
我們在使用 jQuery.validate 1.11.0 和 Microsoft.jQuery.Unobtrusive.Validation 2.0.30116.0 時遇到了同樣的問題。在驗證庫更新的某個地方,數字驗證器壞了。
GitHub 問題跟踪器上有一個與此問題相關的未解決問題:https ://github.com/jzaefferer/jquery-validation/issues/626
在那個問題中引用:
返回 this.optional(element) || ( 值 >= 參數
$$ 0 $$&& 值 <= 參數$$ 1 $$); 因為這一行檢查的是字元串,而不是數字。如果我的範圍在 30 到 200 之間,並且我想驗證 120,則字元串 120 小於字元串 30。
這一行必須是這樣的:
返回 this.optional(element) || (數字(值)>=數字(參數
$$ 0 $$) && 數字(值) <= 數字(參數$$ 1 $$) );
我已經更改了 jquery.validate.js 的副本:
// http://docs.jquery.com/Plugins/Validation/Methods/range range: function( value, element, param ) { return this.optional(element) || (value >= param[0] && value <= param[1]) || (Number(value) >= Number(param[0]) && Number(value) <= Number(param[1])); },現在範圍操作使用 DataAnnotations 按預期工作:
[Range(1, 100)] public decimal Price { get; set; }