2016-03-15 143 views
0

通过正则表达式目录 的我用asp.net的MVC 5.工作,我有一个 List<string>这样的: 验证模型注释

var animals = new List<string> 
{ 
    "Dog", 
    "Cat" 
}; 

animals只能包含2个值:DogCat。所以,如果值为TigerLion,那么这是无效的。

这里是我用来验证的基本途径:

var regex = new Regex(@"Dog|Cat"); 
foreach (string animal in animals) 
{ 
    if (!regex.IsMatch(animal)) 
    { 
     // throw error message here... 
    } 
} 

现在,我要声明的模型Animal存储列表:

class Animal 
{ 
    //[RegularExpression(@"Dog|Cat", ErrorMessage = "Invalid animal")] 
    public List<string> Animals { get; set; } 
} 

在一些行动:

public ActionResult Add(Animal model) 
{ 
    if (ModelState.IsValid) 
    { 
     // do stuff... 
    } 
    // throw error message... 
} 

所以,我的问题是:如何使用正则表达式来验证这一点List<string>值 案件?

回答

2

你可以写自己的属性:

public class ListIsValid : ValidationAttribute 
{ 
    public override bool IsValid(List animals) 
    { 
     var regex = new Regex(@"Dog|Cat"); 
     foreach (string animal in animals) 
     { 
      if (!regex.IsMatch(animal)) 
      { 
       return false; 
      } 
     } 
     return true; 
    } 
} 

在你Animal你的类,然后使用它是这样的:

[ListIsValid(ErrorMessage = "There is some wrong animal in the list")] 
public List<string> Animals { get; set; } 
+0

非常感谢!这是帮助:) –

1

定义自定义验证属性并在那里实现您的自定义逻辑。

public class OnlyDogsAndCatsAttribute : ValidationAttribute 
{ 
    public override bool IsValid(object value) 
    => (value as IList<string>).All(s => s == "Dog" || s == "Cat"); 
} 

public class Animal 
{ 
    [OnlyDogsAndCatsAttribute] 
    public List<string> Animals { get; set; } 
} 

通知没有必要使用正则表达式

+0

谢谢。我会现在试试:) –