这个要使用自定义验证
代码:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public class DateTimeRangeAttribute : ValidationAttribute
{
public int MinAge { get; set; }
public int MaxAge { get; set; }
public DateTimeRangeAttribute()
:base()
{
this.MinAge = 18;
this.MaxAge = 65;
}
public override bool IsValid(object value)
{
DateTime date = DateTime.MinValue;
DateTime.TryParse(value.ToString(), out date);
if (date != DateTime.MinValue)
{
if (date > DateTime.Now.AddYears(-MaxAge) && date < DateTime.Now.AddYears(-MinAge))
{
return true;
}
}
return false;
}
}
在Model中这样写:
[Required]
[DateTimeRange(ErrorMessage = "Age must be between 18 and 65")]
public DateTime Birthday { get; set; }
然后在View中这样写:
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>UserInfo</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Birthday)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Birthday)
@Html.ValidationMessageFor(model => model.Birthday)
</div>
<p>
<input type="submit" value="Create"/>
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
非常感谢你每次回答我的问题啊,小子没豆,只能言谢了。