需要验证的Model
public class Movie
{
public int ID { get; set; }
[StringLength(60, MinimumLength = 3)]
[Required]
public string Title { get; set; }
[Display(Name = "放映日期")]
[DataType(DataType.Date)]
[Range(typeof(DateTime), "1/1/1966", "1/1/2020")]
public DateTime ReleaseDate { get; set; }
[Range(1, 100)]
[DataType(DataType.Currency)]
public decimal Price { get; set; }
[RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
[Required]
[StringLength(30)]
public string Genre { get; set; }
[RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
[StringLength(5)]
[Required]
public string Rating { get; set; }
}
Required 特性表示属性不能为空,但不能校验空格
值类型(如decimal, int, float, DateTime) 本身是必须的,并不需要 [Required] 特性。
Range 特性限制值在指定的范围内。
StringLength 特性可让你设定字符串最大长度,以及最小长度(可选)。
RegularExpression特性校验正则表达式。
注意:禁止在 DateTime 上使用 Range 特性来进行 JQuery 日期验证。因为不管填入的时间值在不在Range范围内,js验证都会提示错误。
public class ProductsDto
{
[Display(Name = "商品编号")]
[Required(ErrorMessage = "{0}是必填项")]
[StringLength(maximumLength: 10, MinimumLength = 5, ErrorMessage = "{0}的长度范围是{2}到{1}")]
public string ProductCode { get; set; }
[Display(Name = "商品名称")]
[Required(ErrorMessage = "{0}是必填项")]
[MinLength(1, ErrorMessage = "{0}的最小长度是1")]
public string ProductName { get; set; }
[Display(Name = "商品价格")]
[Required(ErrorMessage = "{0}是必填项")]
[RegularExpression(@"^(?!.{12,}$)\d{1,18}(\.\d{1,2})?$", ErrorMessage = "{0}格式不规范,{0}要保留小数点后1到2位")]
public decimal? Price { get; set; }
[Display(Name = "会员价")]
[Compare("Price", ErrorMessage = "{0}必须和{1}相同")]
public decimal? VipPrice { get; set; }
[Display(Name = "状态")]
[Range(0, 1, ErrorMessage = "{0}必须是{1}或{2}")]
public int? Status { get; set; }
}