添加自定义验证机制到abpBoilerplate dtos?

时间:2017-07-18 08:27:11

标签: .net dto aspnetboilerplate

我们创建自定义属性" SpecificDateAttribute"对于calss属性。我们如何强制所有具有此属性的属性的DTO,验证ICustomValidate方法?

1 个答案:

答案 0 :(得分:0)

我为Dtos创建了这样的基类:

 public class AzmaBaseDto: ICustomValidate
{
    public virtual void AddAzmValidationErrors(CustomValidationContext context)
    {

    }

    public void AddValidationErrors(CustomValidationContext context)
    {
        var properties = this.GetType()
            .GetProperties();

        foreach (var a in properties.Where(p => p.IsDefined(typeof(ShamsiDateAttribute), false)))
        {
            #region
            var v = a.GetValue(this);
            if (v == null || DateTimeConvert.IsValidShamsiDate(v.ToString()) == false)
            {
                string _name = a.Name;
                if (a.IsDefined(typeof(DisplayAttribute), false))
                {
                    var ca = (DisplayAttribute)a.GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault();
                    if (ca.Name.IsNullOrEmpty() == false)
                        _name = ca.Name;
                }
                context.Results.Add(new ValidationResult("Property value [" + _name + "] is not valid"));
            }
            #endregion
        }

                   AddAzmValidationErrors(context);
    }
}

并继承Dtos形成它。像这样

  public class UpsertAccountingDocumentInput : AzmaBaseDto
{

    [ShamsiDate]
    public string Date { get; set; }



    public bool? SaveAsMemo { get; set; }



    public override void AddAzmValidationErrors(CustomValidationContext context)
    {
        if(SaveAsMemo==false && Date.IsNullOrEmpty()==false)
        {
            context.Results.Add(new ValidationResult("Put some error info"));
        }

        base.AddAzmValidationErrors(context);
    }
}

我认为这可能是正确答案之一。