0

我们为类属性创建自定义属性“SpecificDateAttribute”。我们如何强制所有具有此属性的 DTO 验证 ICustomValidate 方法?

4

1 回答 1

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);
    }
}

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

于 2017-07-23T11:17:35.220 回答