I'm working with asp.net mvc 5. I have a List<string>
like this:
var animals = new List<string>
{
"Dog",
"Cat"
};
animals
can contain only 2 values: Dog
and Cat
. So, that's invalid if the value is Tiger
or Lion
.
Here is the basic way I've used to validate:
var regex = new Regex(@"Dog|Cat");
foreach (string animal in animals)
{
if (!regex.IsMatch(animal))
{
// throw error message here...
}
}
Now, I want to declare a model Animal
to store the List:
class Animal
{
//[RegularExpression(@"Dog|Cat", ErrorMessage = "Invalid animal")]
public List<string> Animals { get; set; }
}
and in some action:
public ActionResult Add(Animal model)
{
if (ModelState.IsValid)
{
// do stuff...
}
// throw error message...
}
So, my question is: how to use regex to validate the value of List<string>
in this case?
Based on diiN's answer:
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;
}
}
Usage:
[RegularExpressionList("your pattern", ErrorMessage = "your message")]
public List<string> Animals { get; set; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With