FluentValidation用于验证不同集合的长度

时间:2015-06-11 16:43:31

标签: c# fluentvalidation

鉴于以下七个数据元素,我必须创建一个验证规则,即元素的集合长度不超过315个字符。 AssetType是类型的枚举器,如果其中一种类型不能准确描述资产,则使用AssetTypeOtherDescription。关于如何实现此验证的任何想法?

COLLATERAL.PLEDGED_ASSET.OWNED_PROPERTY.PROPERTY.ADDRESS.AddressLineText
COLLATERAL.PLEDGED_ASSET.OWNED_PROPERTY.PROPERTY.ADDRESS.CityName
COLLATERAL.PLEDGED_ASSET.OWNED_PROPERTY.PROPERTY.ADDRESS.PostalCode
COLLATERAL.PLEDGED_ASSET.OWNED_PROPERTY.PROPERTY.ADDRESS.StateCode
COLLATERAL.PLEDGED_ASSET.ASSET_DETAIL.AssetType
COLLATERAL.PLEDGED_ASSET.ASSET_DETAIL.AssetTypeOtherDescription
COLLATERAL.PLEDGED_ASSET.OWNED_PROPERTY.PROPERTY.LEGAL_DESCRIPTIONS.LEGAL_DESCRIPTION

1 个答案:

答案 0 :(得分:1)

这个怎么样:

RuleFor(x => x).Must(YourRequest)

private bool YourRequest(COLLATERAL coll)
{
   var result = false;

   //your Logic

   return result;
}

你可以找到一个完整的例子here

private bool YourRequest(COLLATERAL coll)
{
   var result = false;

   if(coll != null 
   && coll.PLEDGED_ASSET_PROPERTY != null
   && coll.PLEDGED_ASSET_PROPERTY.PROPERTY != null
   && coll.PLEDGED_ASSET_PROPERTY.PROPERTY.ADDRESS != null
   && coll.PLEDGED_ASSET.OWNED_PROPERTY != null
   && coll.PLEDGED_ASSET.OWNED_PROPERTY.PROPERTY != null
   && coll.PLEDGED_ASSET.ASSET_DETAIL != null)
   { 
        var charcount = 0;
        charcount += coll.PLEDGED_ASSET.OWNED_PROPERTY.PROPERTY.ADDRESS.AddressLineText.Count()
        charcount += coll.PLEDGED_ASSET.OWNED_PROPERTY.PROPERTY.ADDRESS.CityName.Count()
        charcount += coll.PLEDGED_ASSET.OWNED_PROPERTY.PROPERTY.ADDRESS.PostalCode.Count()
        charcount += coll.PLEDGED_ASSET.OWNED_PROPERTY.PROPERTY.ADDRESS.StateCode.Count()

        charcount += coll.PLEDGED_ASSET.OWNED_PROPERTY.PROPERTY.LEGAL_DESCRIPTIONS.LEGAL_DESCRIPTION


        //one way to check your enumerator 
        bool isNotAccurately =false;
        foreach(var item in coll.PLEDGED_ASSET.ASSET_DETAIL.AssetType)
        {    
            if(item  == //your Logic for "does not accurately describe"
                isNotAccurately = true; 
        }
        if(isNotAccurately )
            charcount += coll.PLEDGED_ASSET.ASSET_DETAIL.AssetTypeOtherDescription
        else
            foreach(var item in coll.PLEDGED_ASSET.ASSET_DETAIL.AssetType)
            {    
                charcount += item.Count();
            }

        if(charcount < 315)
            result = true;
   }

   return result;
}