【发布时间】:2019-12-05 04:04:10
【问题描述】:
我已经建立了一个自定义的正则表达式类。我还有一个数据库值,它是我不希望在我的 Web 应用程序中的任何位置允许的字符列表。我的自定义正则表达式类将采用所有其他正则表达式,并确保不允许我的不需要的字符列表。我的自定义正则表达式类在我的 Global.asax.cs 中注册,并且由于它是数据库中的一个值,因此可以在必要时进行更改。现在我需要做的是找到一种方法来获取正则表达式错误消息并添加类似的内容:“此字段不能包含以下内容:” + mybadcharacterlist;
已经试过了:
public const string AlphaErrMsg = "此字段只能包含字母,此字段不能包含以下字符:" + RestrictedCharacterList.GetList();
这不起作用,因为 RegularExpressionAttribute 的错误参数需要一个 const 并且调用我的 GetList 方法不是一个常量。
protected void Application_Start()
{
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof (RestrictCharRegExpressAttribute), typeof(RegulatExpressionAttributeAdapter);
}
public class RestrictCharRegExpressAttribute : RegularExpressionAttribute
{
public RestrictCharRegExpressAttribute(string propRegex) : base(GetRegex(propRegex)) {}
private static string GetRegex(string propRegex)
{
in indexPropRegex = propRegex.IndexOf('^');
string restrictedCharsAction = "(?!.*[" + RestrictedCharacterList.GetList() + "])";
propRegex = indexPropRegex == -1 ? propRegex.Insert(0, restrictedCharsAction) : propRegex.Insert(indexPropRegex + 1, restrictedCharsAction);
return propRegex;
}
}
public static class RestrictedCharacterList
{
public static string GetList()
{
string restrictedChars;
if (HttpContext.Current?.Session == null)
{
restrictedChars = EnvironmentSettingsDA.GetSetting(AppConfiguration.Settings.ConnectionString, "CAMPS", "RESTRICTED_CHARACTERS");
}
else
{
restrictedChars = HttpContext.Current.Session.GetDataFromSession<string>("RESTRICTED_CHARACTERS");
if (restrictedChars == null)
{
restrictedChars = EnvironmentSettingsDA.GetSetting(AppConfiguration.Settings.ConnectionString, "CAMPS", "RESTRICTED_CHARACTERS");
HttpContext.Current.Session.SetDataToSession<string>("Restricted_Characters", restrictedChars);
}
}
return restrictedChars;
}
}
public class User
{
public const string IsAlphaRegex = "^[a-zA-Z]*$'
public const string AlphaErrMsg = "This field can only contain letters.";
[RestrictCharRegExpress(IsAlphaRegex, ErrorMessage = AlphaErrMsg)]
public string FirstName { get; set; }
}
预期的结果是在我的所有正则表达式错误消息中添加一条消息,描述不允许使用哪些字符,同时确保可以在数据库中更改字符列表。
【问题讨论】:
-
注意
"^[a-zA-Z]*$应该以"结尾。字符列表中需要转义的字符是\、]、^和-。所以,使用RestrictedCharacterList.GetList().Replace("^","\\^")).Replace("\\","\\\\")).Replace("]","\\]")).Replace("-","\\-") -
@WiktorStribiżew 出于某种原因,我不必这样做。当从数据库中提取字符时,C# 可能会自行转义它们?无论哪种方式,我都不必执行任何特殊的替换命令。
-
那么你最终会得到与你期望不同的匹配的损坏模式。
-
@WiktorStribiżew 此评论适用于将来可能会看到此页面的任何其他人。维克托你完全正确,我错了。我之前没有任何问题,因为我并没有试图排除这些字符,但是他们需要阻止反斜杠并且它不起作用。我包括了你的建议,它工作正常。所以谢谢你。
标签: c# regex asp.net-mvc