public class Product : IValidatableObject
{
/// <summary>
/// 产品名称
/// </summary>
[DisplayName("产品名称")]
[AllowHtml]//允许输入html脚本
[Required]
[DataType(DataType.DateTime)]
public String Name { get; set; }
/// <summary>
/// 库存数量
/// </summary>
[DisplayName("库存")]
[Required]
[EmailAddress]
[RegularExpression("",ErrorMessage ="")]
[System.Web.Mvc.Compare(nameof(Shipping))]
[Range(10,20,ErrorMessage ="")]
public int Inventory { get; set; }
/// <summary>
/// 销售数量
/// </summary>
[DisplayName("售出")]
[Required]
public int Shipping { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
Type type = typeof(Product);
EntityAttribute entityAttribute = new EntityAttribute(type);
PropertyInfo[] PropertyInfos = type.GetProperties();
string shippingDisplayName = entityAttribute.GetDisplayAttributeName("Shipping");
string inventoryDisplayName = entityAttribute.GetDisplayAttributeName("Inventory");
if (Shipping > Inventory)
{
yield return new ValidationResult(string.Format("{0}数量不能大于{1}数量", shippingDisplayName, inventoryDisplayName), new string[] { "Shipping" });
}
}
}