我正在使用 asp.net mvc 5。我有List<string>这样的:
var animals = new List<string>
{
"Dog",
"Cat"
};
Run Code Online (Sandbox Code Playgroud)
animals只能包含 2 个值:Dog和Cat。因此,如果值为Tiger或 ,则无效Lion。
这是我用来验证的基本方法:
var regex = new Regex(@"Dog|Cat");
foreach (string animal in animals)
{
if (!regex.IsMatch(animal))
{
// throw error message here...
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我想声明一个模型Animal来存储列表:
class Animal
{
//[RegularExpression(@"Dog|Cat", ErrorMessage = "Invalid animal")]
public List<string> Animals { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
并在某些行动中:
public ActionResult Add(Animal model)
{
if (ModelState.IsValid)
{
// do stuff...
}
// throw error message...
}
Run Code Online (Sandbox Code Playgroud)
List<string>所以,我的问题是:在这种情况下如何使用正则表达式来验证 的值?
根据diiN 的回答:
public class RegularExpressionListAttribute : RegularExpressionAttribute
{
public RegularExpressionListAttribute(string pattern)
: base(pattern) { }
public override bool IsValid(object value)
{
if (value is not IEnumerable<string>)
return false;
foreach (var val in value as IEnumerable<string>)
{
if (!Regex.IsMatch(val, Pattern))
return false;
}
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
[RegularExpressionList("your pattern", ErrorMessage = "your message")]
public List<string> Animals { get; set; }
Run Code Online (Sandbox Code Playgroud)