我的模型中有两个字段
,像这样呈现
<b>Start Date</b> @Html.EditorFor(model => model.AdvanceSearch.CreateDatefrom, new { @class = "picker startDate" })
<b>End Date</b> @Html.EditorFor(model => model.AdvanceSearch.CreateDateto, new { @class = "picker endDate" })
我有一个验证方案,enddate不应该大于开始日期,目前我通过jquery验证它
$.validator.addMethod("endDate", function (value, element) {
var startDate = $('.startDate').val();
return Date.parse(startDate) <= Date.parse(value);
}, "* End date must be Equal/After start date");
我想知道在MVC3模型验证中有什么方法可以做到这一点吗?
答案 0 :(得分:6)
我会说你不应该只依赖Javascript,除非你在某种内联网应用程序中控制你的客户端的浏览器。如果应用程序面向公众 - 请确保您同时进行客户端和服务器端验证。
此外,可以使用下面显示的自定义验证属性在模型对象中实现服务器端验证的更简洁方法。然后,您的验证将变为集中,您无需明确比较控制器中的日期。
public class MustBeGreaterThanAttribute : ValidationAttribute
{
private readonly string _otherProperty;
public MustBeGreaterThanAttribute(string otherProperty, string errorMessage) : base(errorMessage)
{
_otherProperty = otherProperty;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var otherProperty = validationContext.ObjectInstance.GetType().GetProperty(_otherProperty);
var otherValue = otherProperty.GetValue(validationContext.ObjectInstance, null);
var thisDateValue = Convert.ToDateTime(value);
var otherDateValue = Convert.ToDateTime(otherValue);
if (thisDateValue > otherDateValue)
{
return ValidationResult.Success;
}
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
}
然后可以将其应用于您的模型,如下所示:
public class MyViewModel
{
[MustBeGreaterThan("End", "Start date must be greater than End date")]
public DateTime Start { get; set; }
public DateTime End { get; set; }
// more properties...
}
答案 1 :(得分:2)
您需要针对模型创建自定义验证。你可以在if(Model.IsValid)
之后将它放在控制器中if(Model.End<Model.StartDate)
....
但我会坚持使用javascript。 它适用于客户端,并且不会命中服务器。 除非你只是需要额外的保证。