是否可以为MVC 3中的StringLength验证器提供运行时值?

val*_*lik 6 validation asp.net-mvc data-annotations

我正在使用数据注释验证MVC 3中的字段:

[StringLength(50, MinimumLength=5)]
public string MyText { get; set; }
Run Code Online (Sandbox Code Playgroud)

有没有办法在那里提供动态价值?像这样的东西:

[StringLength(50, MinimumLength=GetMinimumLengthValueFromDb())]
public string MyText { get; set; }
Run Code Online (Sandbox Code Playgroud)

我的最后一招是使用远程验证器.如果我找不到办法StringLength,我会用RemoteValidator.

Joã*_*elo 7

不,只能为属性提供编译时间值,如常量.此限制适用于所有C#属性,并不特定于数据注释属性,但在这种情况下StringLengthAttribute暗示有可能在运行时提供不同的长度.

您需要使用其他类型的验证,或者创建继承自StringLengthAttribute该类型的自定义属性,并接受Type该类型上的方法名称作为长度值的来源.这种方法类似于CustomValidationAttribute接受a ValidatorTypeMethod名称作为验证来源的方法.