Search code examples
c#.netvalidationasp.net-mvc-2asp.net-mvc-validation

How to validate properties in 2 different situations in mvc 2 app?


please help me with asp.net MVC 2 application.

I have class:

public class Account
{
    [Required(....)]
    [RegularExpression("....")]
    public string AccountCode{ get; set; } 

    public string BankName{ get;  set; } 
}

And another one:

public class BankPageModel
{
    public bool AccountRequired {get; set; }
    public Account NewAccount {get;set;}
}

Imagine I have page and form on it with 2 text boxes (AccountCode and BankName) and check box (AccountRequired). So when I post the form, if check box is checked, I want to validate AccountCode to be required and to fit regular expression. But if it is not checked, I just want to ignore those text boxes and to post the form. But Required and RegularExpression attributes cannot be used then, they are preventing it. I could make class attribute, but what if I have more textboxes with similar validation, I don't want to make class attribute for each of them... What do you think? Thanks in advance.


Solution

  • The best way to do this on the server side, is to have your model implement IValidatableObject and then do the following:

    public class BankPageModel : System.ComponentModel.DataAnnotations.IValidatableObject
    {
        public bool AccountRequired { get; set; }
        public Account NewAccount { get; set; }
    
        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            // only perform validation here if account required is checked
            if (this.AccountRequired)
            {
                // check your regex here for account
                if (!RegEx.IsMatch(this.NewAccount.AccountCode, "EXPRESSION"))
                {
                    yield return new ValidationResult("Error");
                }
            }
        }
    }     
    

    Doing things this way helps keep your controllers lean and encapsulates all validation logic in your model. This method could also be verified client side with unobtrusive javascript.