如何为两个属性创建验证属性MVC

时间:2014-09-08 17:35:55

标签: c# asp.net-mvc validation

public class Product
{
    public int Id { get; set; }

    [Required(ErrorMessage = "Please enter name")]
    [StringLength(60, MinimumLength = 2)]
    [Remote("ValidateProductName", "Products", ErrorMessage = "Product with this name already exist")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Please enter price")]
    [Range(0.1, double.MaxValue, ErrorMessage = "Price must be greater than 0")]
    public decimal Price { get; set; }

    [Required(ErrorMessage = "Please enter quantity")]
    [DataType(DataType.Currency)]
    //[Range(0, int.MaxValue, ErrorMessage = "The value must be greater than 0")]
    public int Quantity { get; set; }

    [Required(ErrorMessage = "Please enter date")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
    //[DateRange("01/01/2050")]
    [CurrentDate(ErrorMessage = "You enter invalid data")]
    public DateTime DeliveryDate { get; set; }

    [Required(ErrorMessage = "Please enter if is in promotion")]
    public bool InPromotion { get; set; }
}

我想检查数量是多个价格是否大于100 000,如果更大则写错误消息。我需要使用属性。有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

您需要为逻辑定义自定义属性。

public class ValidatePriceAttribute: ValidationAttribute
{
    private double maxVal = 0.0;
    public ValidatePriceAttribute(double maxVal)
    {
       this.maxVal = maxVal;
    }

    protected override ValidationResult IsValid(object value, ValidationContext ctx)
    {
        var obj = ctx.ObjectInstance as Product;

        if (obj != null) {
              if( obj.Price * obj.Quantity > this.maxVal){
                     return new ValidationResult("error message goes here");
              }
        } 

       return null;
    }
}

使用

[ValidatePrice(100000.0)]
public double Price {get;set;}

以上代码仅供参考,需要进行大量改进才能使其更加灵活和通用,我将此练习留给您:)