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; }
You could write your own attribute:
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;
}
}
In your Animal
class you then use it like this:
[ListIsValid(ErrorMessage = "There is some wrong animal in the list")]
public List<string> Animals { get; set; }
Define custom Validation attribute and implement your custom logic there.
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; }
}
Notice no need to use regex
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.