【问题标题】:Is it possible to provide a runtime value to StringLength validator in MVC 3?是否可以在 MVC 3 中为 StringLength 验证器提供运行时值?
【发布时间】:2025-11-29 08:15:01
【问题描述】:

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

[StringLength(50, MinimumLength=5)]
public string MyText { get; set; }

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

[StringLength(50, MinimumLength=GetMinimumLengthValueFromDb())]
public string MyText { get; set; }

我最后的手段是使用远程验证器。如果我找不到使用StringLength 的方法,我将使用RemoteValidator

【问题讨论】:

  • 我将扩展 StringLenghtAttribute 类,仅覆盖构造函数以从 db 中检索默认值。

标签: asp.net-mvc validation data-annotations


【解决方案1】:

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

您需要使用另一种验证,或者可能创建一个继承自 StringLengthAttribute 的自定义属性,该属性接受 Type 和该类型上的方法名称作为长度值的来源。这种方法类似于CustomValidationAttribute 使用的方法,它接受ValidatorTypeMethod 名称作为验证源。

【讨论】:

  • 谢谢。我按照您描述的方式实现了验证-从 StringLengthAttribute 继承并对其进行了本地化,并添加了用于从 DB 中选择自定义最小长度值的逻辑
  • 感谢您指向CustomValidationAttribute!我完全忘记了这一点:-)
  • @valerii.sverdlik:是否可以分享您使用的代码?
最近更新 更多