Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation of List<string> via regex in model annotation

Tags:

c#

regex

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?

like image 978
Tân Avatar asked Sep 03 '25 14:09

Tân


1 Answers

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; }
like image 61
Sasan Avatar answered Sep 05 '25 06:09

Sasan