我想以dd-mmm-yyyy的形式强制执行日期。我正在使用以下帖子作为指南:
问题: ValidationMessageFor文本将不会显示(在回发和客户端)。有什么建议吗?
更新
通过包含@ Darin-Demintrov的答案,此问题中的代码现在可以正常运行。请注意,选择日期后验证消息仍然存在。要解决此问题,必须根据下面的答案处理DatePicker onChange()事件。
查看模型属性:
[Required(ErrorMessage = "* required")]
[Display(Name = "Event Date")]
[PpcDate]
public DateTime EventDate { get; set; }
PpcDate ValidationAttribute类:
public class PpcDateAttribute : ValidationAttribute, IClientValidatable, IMetadataAware
{
/// <summary>
/// Any valid DateTime is fine;
/// the regex verification only happens on the client
/// </summary>
public override bool IsValid(object value)
{
if (value == null || (value is DateTime))
return true;
else
return false;
}
public override string FormatErrorMessage(string name)
{
return string.Format("{0} must be in the form dd-mmm-yyyy", name);
}
#region IClientValidatable Members
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.DisplayName),
ValidationType = "ppcdate"
};
}
#endregion
#region IMetadataAware Members
public void OnMetadataCreated(ModelMetadata metadata)
{
metadata.DataTypeName = "Date";
}
#endregion
}
视图:
@Html.EditorFor(model => model.EventDate)
@Html.ValidationMessageFor(model => model.EventDate)
与javascript联系:
(function ($) {
// The validator function
$.validator.addMethod('ppcdate', function (value) {
if (!value) {
return true;
} else {
return /^\d{2}-\w{3}-\d{4}$/.test(value);
}
});
// The adapter to support ASP.NET MVC unobtrusive validation
$.validator.unobtrusive.adapters.add('ppcdate', [], function (options) {
// EDIT: Add next line per Darin's answer below.
options.rules['ppcdate'] = true;
if (options.message) {
options.messages['ppcdate'] = options.message;
}
});
} (jQuery));
结果html肯定看起来不错?
请注意,data-val-ppcdate属性显示为预期...
<div class="t-widget t-datepicker">
<div class="t-picker-wrap">
<input autocomplete="off" class="t-input valid" data-val="true" data-val-ppcdate="Event Date must be in the form dd-mmm-yyyy" data-val-required="* required" id="EventDate" name="EventDate" value="28-Sep-2011" type="text">
<span class="t-select">
<span class="t-icon t-icon-calendar" title="Open the calendar">Open the calendar</span>
</span>
</div>
</div>
<span class="field-validation-valid" data-valmsg-for="EventDate" data-valmsg-replace="true"></span>
有什么建议吗?
答案 0 :(得分:3)
您忘记注册规则,并且您的自定义ppcdate
验证方法永远不会触发:
$.validator.unobtrusive.adapters.add('ppcdate', [], function (options) {
if (options.message) {
// This is what associates the adapter with the custom validation method
options.rules['ppcdate'] = options.params;
options.messages['ppcdate'] = options.message;
}
});
这是一个完整的example。
答案 1 :(得分:0)
加载fiddler并查看您的CSS文件是否未加载。我知道如果CSS没有加载,摘要将不会显示,所以我必须假设同样适用于单个验证项。
答案 2 :(得分:0)
Date.ascx文件(日期控制):
<%= Html.Telerik().DatePickerFor(m => m)
.Format("dd-MMM-yyyy")
.Value(ViewData["selectedDate"] as DateTime?)
.ClientEvents(e => { e.OnChange("PPC_validateTelerikDate"); })
%>
<强>的Javascript 强>
/*****************************************************************************
PPC_validateTelerikDate()
Force validation to run on the target input.
This function allows one to validate when the date picker changes.
Otherwise, validation only runs when clicking the input element directly
or tabbing through.
*****************************************************************************/
function PPC_validateTelerikDate(e) {
// get the form validation object
var val = $(e.target.form).validate();
// now validate the target
val.element($(e.target));
}