如何编写自定义的RegularExpressionValidator,它从配置文件中获取值?

nim*_*imi 9 asp.net-mvc data-annotations

我必须在我的模型中为username属性使用Regular表达式验证器.我从配置文件中获取此正则表达式.

[RegularExpression(UsernameValidationExpression)] //UsernameValidationExpression = value from the config file
public string UserName { get; set; }
Run Code Online (Sandbox Code Playgroud)

这里我得到一个错误"属性参数必须是属性参数类型的常量表达式,typeof表达式或数组创建表达式"

我怎么解决这个?

Dar*_*rov 13

public class ConfigRegularExpressionAttribute : RegularExpressionAttribute
{
    public ConfigRegularExpressionAttribute(string patternConfigKey)
        : base(ConfigurationManager.AppSettings[patternConfigKey])
    { }
}
Run Code Online (Sandbox Code Playgroud)

然后:

[ConfigRegularExpression("UsernameValidationExpression")]
public string UserName { get; set; }
Run Code Online (Sandbox Code Playgroud)

并在web.config中:

<appSettings>
    <add key="UsernameValidationExpression" value="foo bar" />
</appSettings>
Run Code Online (Sandbox Code Playgroud)