我需要在StartDate和EndDate上进行验证
验证:
到目前为止我的代码:
对象:
[DisplayName("Effective Start Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime EffectiveStartDate { get; set; }
[DisplayName("Effective End Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime EffectiveEndDate { get; set; }
查看:
</tr>
<tr>
<td class="lables"><%= Html.LabelFor(model => model.EffectiveEndDate)%></td>
<td class="data" id = "endDate"><%= Html.EditorFor(model => model.EffectiveEndDate)%>
<%= Html.ValidationMessageFor(model => model.EffectiveEndDate)%></td>
</tr>
<tr>
<td class="lables"><%= Html.LabelFor(model => model.ErrorCheckEnabled)%></td>
<td class="data" ><%= Html.TextAreaFor(model => model.ErrorCheckEnabled)%>
<%= Html.ValidationMessageFor(model => model.EffectiveEndDate)%></td>
</tr>
我应该如何进行验证。我应该在客户端网站上做什么
$("#frm").validate
[或]
???
答案 0 :(得分:1)
必须说明:您应该始终进行服务器端验证,因为用户可以关闭javascript,因此您的验证将不会应用。但我建议进行客户端验证,以便UX更好。服务器端和客户端验证可以很容易地同时存在。
对于服务器端,您可以通过从ValidationAttribute类派生来轻松创建自己的验证属性。看看这个例子:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class EndDateAttribute : ValidationAttribute
{
public EndDateAttribute(DateTime endDate)
{
EndDate = endDate;
}
public DateTime EndDate { get; set; }
public override bool IsValid(object value)
{
if (value == null)
return false;
DateTime val;
try
{
val = (DateTime)value;
}
catch (InvalidCastException)
{
return false;
}
if (val >= EndDate)
return false;
return true;
}
}
你可以弄清楚如何制作StartDate。
更新:使用它非常简单。您只需将其作为任何其他(验证)属性应用于您的属性。例如
[DisplayName("Effective Start Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
[StartDate(DateTime.Now)]
public DateTime EffectiveStartDate { get; set; }
[DisplayName("Effective End Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
[EndDate(new DateTime(2011, 9, 24)]
public DateTime EffectiveEndDate { get; set; }