Entlib验证语法只接受数字月份数字?

时间:2010-03-18 15:42:32

标签: validation enums integer enterprise-library

我已经定义了这样的枚举:

Private Enum AllowedMonthNumbers
    _1
    _2
    _3
    _4
    _5
    _6
    _7
    _8
    _9
    _10
    _11
    _12
End Enum

然后将属性验证器定义为:

<TypeConversionValidator(GetType(Int32), MessageTemplate:="Card expiry month must be numeric.", Ruleset:="CreditCard")> _
<EnumConversionValidator(GetType(AllowedMonthNumbers), MessageTemplate:="Card expiry month must be between 1 and 12.", Ruleset:="CreditCard")> _

验证需要“_#”,因为当我删除TypeConversionValidator时,它会将值设置为“_3”或枚举中的任何其他数字。

我需要的是只接受b / t 1-12,并且只需在枚举中使用数值即可。

任何提示?

感谢。

更新

我用RangeValidator替换了EnumConversionValidator,并尝试将参数设置为“1”,但收到以下错误:

<RangeValidator(1, RangeBoundaryType.Inclusive, 12, RangeBoundaryType.Inclusive, MessageTemplate:="..."> 

然而现在这给了我以下错误:

System.Web.Services.Protocols.SoapException : System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.ArgumentException: Object must be of type Int32.
   at System.Int32.CompareTo(Object value)
   at Microsoft.Practices.EnterpriseLibrary.Validation.Validators.RangeChecker`1.IsInRange(T target)
   at Microsoft.Practices.EnterpriseLibrary.Validation.Validators.RangeValidator`1.DoValidate(T objectToValidate, Object currentTarget, String key, ValidationResults validationResults)
   at Microsoft.Practices.EnterpriseLibrary.Validation.Validator`1.DoValidate(Object objectToValidate, Object currentTarget, String key, ValidationResults validationResults)
   at Microsoft.Practices.EnterpriseLibrary.Validation.Validators.AndCompositeValidator.DoValidate(Object objectToValidate, Object currentTarget, String key, ValidationResults validationResults)
   at Microsoft.Practices.EnterpriseLibrary.Validation.Validators.ValueAccessValidator.DoValidate(Object objectToValidate, Object currentTarget, String key, ValidationResults validationResults)
   at Microsoft.Practices.EnterpriseLibrary.Validation.Validators.AndCompositeValidator.DoValidate(Object objectToValidate, Object currentTarget, String key, ValidationResults validationResults)
   at Microsoft.Practices.EnterpriseLibrary.Validation.Validators.GenericValidatorWrapper`1.DoValidate(T objectToValidate, Object currentTarget, String key, ValidationResults validationResults)
   at Microsoft.Practices.EnterpriseLibrary.Validation.Validator`1.Validate(T target, ValidationResults validationResults)
   at Microsoft.Practices.EnterpriseLibrary.Validation.Validation.Validate[T](T target, String[] rulesets)
   at ....

1 个答案:

答案 0 :(得分:0)

RangeValidator只能处理原始类型,如int,float,double,decimal。因为你在构造函数中提供了一个整数,所以它试图将那个int与你的枚举匹配,这将失败,因为VAB使用Object.Compare(object)方法。

尝试使用您不必将数字范围定义为枚举的设计。请尝试使用简单的整数字段。痛苦少得多。