Grentley
Grentley

Reputation: 437

How to apply different regular expression to view model property?

I have the following view model in asp.net mvc app.

[Required]
public string Name { get; set; }
[Required]
public int Age { get; set; }
public DateTime DateOfBirth { get; set; }
public Address CurrentAddress { get; set; }

My Address object contains Post Code property, that has RegularExpession attribute to validate UK post codes.

public class Address
{
   ...
   [RegularExpression(@"^[A-Z]{1,2}[0-9][0-9A-Z]? [0-9][A-Z]{2}$")]
   public string PostCode { get; set; }
   ...
}

I want to expand the current functionality to validate PostCode using different regular expression when for example person is non-Uk resident.

Any ideas how I could achieve that? Is there any way to modify regular expression value at run-time? If you need more information, please let me know and I'll update the question.

Upvotes: 0

Views: 2831

Answers (1)

eocron
eocron

Reputation: 7526

You can create your own Person dependand attribute:

public class MyTestAttribute : ValidationAttribute
{
    private readonly Regex _regex1;
    private readonly Regex _regex2;

    public MyTestAttribute(string regex1, string regex2)
    {
        _regex1 = new Regex(regex1);
        _regex2 = new Regex(regex2);
    }

    public override bool Match(object obj)
    {
        var input = (string) obj;
        if (IsUk())
        {
            return _regex1.IsMatch(input);
        }
        return _regex2.IsMatch(input);
    }

    private bool IsUk()
    {
        //is person in UK
    }
}

Upvotes: 1

Related Questions