因此,我通过jquery实现了客户端验证。我正试图在服务器端的应用程序中实现同样的验证。
这个属性是字典类型的,我很难找到如何做到这一点的例子。我不能将regex规则添加到属性声明中,因为字典中的每个键都需要不同的regex验证。
例如,在我的控制器GET方法中,我初始化了字典:
model.pt_Left = new Dictionary<string, string>
{
{ "Key1", "" },
{ "Key2", "" },
{ "Key3, "" },
{ "Key4", "" },
};这些键中的每一个都表示视图上的输入字段。它们都有自己的regex验证,这是我在视图中所做的。
我不确定这是否可以在服务器端实现。我不能将正则表达式添加到属性的声明中,因为这会将表达式放在我所有的“键”上
[Required]
public Dictionary<string, string> pt_Left { get; set; }我所拥有的正则表达式的一个例子是^[0-9]{2}[.][0-9]{2}[\/][0-9]{2}[.][0-9]{2}$ --这仅适用于Key1,键2-4每个都有自己的regex验证,这是不同的。
发布于 2021-12-08 05:27:04
因为每个regex模式都是唯一的,这意味着您的不能有一个厨房水槽一个大小适合所有的模式。
但是..。
为什么不扩展您的字典,使每个键包含数据字符串和具有处理/验证对象的逻辑的模式?
有点像
public class Data
{
public string Value { get; set; }
public readonly string Pattern { get; set; }
public IsValid => Regex.IsMatch(Value, Pattern);
public override string ToString() => Value;
}那么您的字典就有了这些扩展的数据。
new Dictionary<string, Data>
{
{ "Key1", new Data() { Value = "1", Pattern = "^[0-9]..." },
{ "Key2", new Data() { Value = "2...", Pattern = "^\w+..." },
{ "Key3, new Data() { Value = "3...", Pattern = "^[a-d]..." },
{ "Key4", new Data() { Value = "4...", Pattern = "^[0-9]..." },
};然后,您已经创建了一个具有操作和验证的面向对象数据类,而不仅仅是一个字符串。IsValid和重写ToString的使用应该比旧字符串更好。
https://stackoverflow.com/questions/62131268
复制相似问题