问题在Collection属性上创建自定义验证器

时间:2011-08-09 07:42:17

标签: asp.net-mvc-3 validation

Net MVC 3用于开发。 现在有一种情况我需要在集合属性上创建自定义验证器。 现在我遇到的问题是,当集合的长度为1时,这个自定义验证器工作得很好但是当集合中有多个元素时我面临一个问题是自定义验证会推送错误但是在签入时会出现问题未找到插入错误的ModelState。那么在这种情况下我该怎么办?我在下面的代码中粘贴。

这是我要验证的模型:

public class CreateTestModel
{
    [Required]
    public string Name { get; set; }

    public string Description { get; set; }

    public RadioButtonListViewModel<GoalTypes> Goals { get; set; }

    [MinimumRequired("IncludedEntities", "ExcludedEntities", 1, ErrorMessage = "1   Entity is compulsory")]
    public IEnumerable<TestEntityModel> IncludedEntities { get; set; }

    public IEnumerable<TestEntityModel> ExcludedEntities { get; set; }

    public IEnumerable<TestFilterModel> IncludedFilters { get; set; }

    public IEnumerable<TestFilterModel> ExcludedFilters { get; set; }

    public IEnumerable<BucketModel> Buckets { get; set; }

    public bool AutoDecision { get; set; }

    public DateTime StartDate { get; set; }

    public DateTime EndDate { get; set; }

    public int AdminId { get; set; }

    [DefaultValue(true)]
    public bool IsEnabled { get; set; }
  }

自定义验证器的用途: - 我需要验证集合中所需实体的最小数量。 在某些情况下,例如在这种情况下:IncludedEntities和ExcludedEntities需要的最小数量为1,包括两个属性,这是我的业务规则。 因此,为此编写了下面的自定义验证器。

这是我写过的自定义验证器:

  [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class MinimumRequired : ValidationAttribute,IClientValidatable
{
    public int numberOfMandatoryEntities{get; private set;}
    public int totalCountofIncludeEntities { get; private set; }
    public bool isBucket { get; set; }
    public string Property1{get; private set;}
    public string Property2{ get; private set; }
    private const string DefaultErrorMessageFormatString = "Atleast one entity is required";

    public MinimumRequired(string Property1, string Property2, int MandatoryCount)
    {
        this.Property1 = Property1;
        if (!String.IsNullOrEmpty(Property2))
            this.Property2 = Property2;
        numberOfMandatoryEntities = MandatoryCount;
    }


    public override string FormatErrorMessage(string name)
    {
        return string.Format(ErrorMessageString, name);
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        object property2Value = null;
        object property1Value = null;
        int property1Count=0;
        if(!String.IsNullOrEmpty(Property2))
        property2Value = validationContext.ObjectInstance.GetType().GetProperty(Property2).GetValue(validationContext.ObjectInstance, null);
        property1Value = validationContext.ObjectInstance.GetType().GetProperty(Property1).GetValue(validationContext.ObjectInstance, null);
        if (property1Value != null)
        {
        property1Count = ((IEnumerable<Object>)property1Value).Count();
        }

        if (property2Value != null)
        {
            property1Count = property1Count + ((IEnumerable<Object>)property2Value).Count();
        }
        if (property1Count < numberOfMandatoryEntities)
        {
            return new ValidationResult(ErrorMessage);
        }

        return ValidationResult.Success;
    }
    #region IClientValidatable Members

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var x = new ModelClientValidationRule();
        x.ValidationType = "entityvalidator";
        x.ErrorMessage = string.Format(ErrorMessageString, metadata.GetDisplayName());
        x.ValidationParameters.Add("mandatoryentity", numberOfMandatoryEntities);
        return new[] 
        {  
            x
        };
    }

    #endregion



}

请帮帮我......

1 个答案:

答案 0 :(得分:0)

我转而使用上面的代码,它对我来说非常适合。