我构建了一个自定义验证属性,允许我检查相对日期(例如模型值小于或等于今天)。
验证器正确实现了该GetClientValidationRules
方法,并且视图中发出的 HTML5对我来说看起来是正确的:
<div class="editor-label">
<label for="Date">Date</label>
</div>
<div class="editor-field">
<input class="text-box single-line" data-val="true" data-val-date="The field Date must be a date." data-val-relativedate="Date must be less than or equal to 12/04/2012" data-val-relativedate-referencedate="12/04/2012 00:00:00" data-val-relativedate-relativityoperator="lessThanOrEqual" data-val-required="The Date field is required." id="Date" name="Date" type="date" value="" />
<span class="field-validation-valid" data-valmsg-for="Date" data-valmsg-replace="true"></span>
</div>
下一步是定义一个自定义的jQuery Unobtrusive Validator适配器和方法:
// Validation Method: Relative Date
// Note: method name value does NOT need to match the HTML5 metadata built by the server model annotation attribute.
$.validator.addMethod("validateRelativeDate", function (value, element, params) {
// "element" is the actual HTML element we are validating, and is unneeded here.
// "value" is the value of the HTML element
var toValidate = DateUtilities.convert(value);
// "params" is a JSON collection of those values provided by the adapter.
var referenceDate = params["referencedate"];
var relativityOperator = params["relativityoperator"];
if (relativityOperator != "lessThan" && relativityOperator != "lessThanOrEqual" || relativityOperator != "greaterThan" && relativityOperator != "greaterThanOrEqual")
return false; // "Invalid relativity operator (ex. '<', '<=', '>', or '>=').");
var toReference = referenceDate == null ? new Date() : referenceDate;
var relativity = DateUtilities.compare(toValidate, toReference);
switch(relativityOperator) {
case "lessThan":
if (relativity >= 0) return false; //"Date must be lesser than " + toReference);
break;
case "lessThanOrEqual":
if (relativity > 0) return false; //"Date must be less than or equal to " + toReference);
break;
case "greaterThan":
if (relativity <= 0) return false; //"Date must be greater than " + toReference);
break;
case "greaterThanOrEqual":
if (relativity < 0) return false; //"Date must be greater than or equal to " + toReference);
break;
}
return true;
});
// note: adapter name must match HTML metadata built by the server model annotation attribute
$.validator.unobtrusive.adapters.add("relativedate", ["referencedate", "relativityoperator"], function (options) {
options.rules["relativedate"] = options.params;
options.messages["relativedate"] = options.message;
});
症状
日期验证已损坏。必需的似乎工作正常。但是,每当我在此字段中键入任何值时,日期类型验证器都会触发并生成消息“日期字段必须是日期”。输入的任何日期值都会发生这种情况。
问题
我的验证规则有什么问题,它 (1) 不起作用,并且 (2) 破坏了 Date 类型验证?