我想为 MVC.NET 框架编写一个自定义验证器,检查输入的日期是否在未来。为此,我编写了以下类:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class InTheFutureAttribute : ValidationAttribute, IClientValidatable
{
private const string DefaultErrorMessage = "{0} should be date in the future";
public InTheFutureAttribute()
: base(DefaultErrorMessage)
{
}
public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, name);
}
public override bool IsValid(object value)
{
DateTime time = (DateTime)value;
if (time < DateTime.Now)
{
return false;
}
return true;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var clientValidationRule = new ModelClientValidationRule()
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "wrongvalue"
};
return new[] { clientValidationRule };
}
}
并将属性添加到我要检查的字段。
在查看页面上,我通过以下方式创建输入字段:
<div class="editor-label-search">
@Html.LabelFor(model => model.checkIn)
</div>
<div class="editor-field-search-date">
@Html.EditorFor(model => model.checkIn)
<script type="text/javascript">
$(document).ready(function ()
{ $('#checkIn').datepicker({ showOn: 'button', buttonImage: '/Content/images/calendar.gif', duration: 0, dateFormat: 'dd/mm/yy' }); });
</script>
@Html.ValidationMessageFor(model => model.checkIn)
</div>
当我为需要在我的验证器中检查属性代码的模型的控制器提交表单时,它会返回 false,但它不会显示错误,而是调用我的控制器的操作并向其发送无效模型。
难道我做错了什么?我该如何解决?