日期:2014-05-20 浏览次数:20541 次
namespace Biz.WEB
{
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false,Inherited=true)]
public class DateAttribute : ValidationAttribute
{
public DateAttribute()
{
MinDate = new DateTime(1753, 1, 1).ToString();
MaxDate = new DateTime(9999, 12, 31).ToString();
}
public string MinDate
{
get;
set;
}
public string MaxDate
{
get;
set;
}
private DateTime minDate, maxDate;
private bool isFormatError = true;
public override bool IsValid(object value)
{
if (value == null || string.IsNullOrEmpty(value.ToString()))
return true;
string s = value.ToString();
minDate = DateTime.Parse(MinDate);
maxDate = DateTime.Parse(MaxDate);
bool result = true;
try
{
DateTime date = DateTime.Parse(s);
isFormatError = false;
if (date > maxDate || date < minDate)
result = false;
}
catch (Exception)
{
result = false;
}
return result;
}
public override string FormatErrorMessage(string name)
{
if (isFormatError)
return "请输入合法的日期";
return base.FormatErrorMessage(name);
}
}
}
namespace MvcApplication4.Models
{
public class Movie
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[StringLength(10, MinimumLength = 2, ErrorMessage = "必须是2~10个字符长"), Required, Display(Name = "名称")]
public string Title { get; set; }
[Date(MaxDate = "2012-01-01", ErrorMessage = "2012地球灭亡啦"), Display(Name = "日期")]
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
[Range(1, 100, ErrorMessage = "必须是1~100")]
public decimal Price { get; set; }
public string Rating { get; set; }
}
public class MovieDBContext : DbContext
{
public DbSet<Movie> Movies { get; set; }
}
}