Frage

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.

War es hilfreich?

Lösung

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.

Andere Tipps

You don't need to use DataAnnotations to perform validation, they just make things easier for common validation scenarios (and you can get client side JavaScript validation for free too).

You can always perform the validation in C# code in your Controller action like below:

public ViewResult BankPageAdd(BankPageModel model)
{
    if(model.AccountRequired &&
        (String.IsNullOrWhiteSpace(model.Account.AccountCode) || !Regex.IsMatch(model.Account.AccountCode, "PATTERN HERE"))
        ModelState.AddModelError("NewAccount.AccountCode", "ERROR MESSAGE HERE");

    //remainder of your controller action code here
}

And the javaScript version:

function validateAccountCode() {
        var bCkd = document.getElementById("ckbxAccountRequired").checked;

        if (bCkd) {
           var accountCode = document.forms[0].elements["AccountCode"].value;
            if(!accountCode.match(yourRegEx) || accountCode==""){
               alert('Please fill in the Account Code');
               return false;
            }
            return true;
        }
        return true;
    }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top