Zdenek G
Zdenek G

Reputation: 351

Different validation on insert and edit

I'm using DataAnotation for validation and i need disable it of in some cases.

F.E. on create i need user insert password and confirmation, but for edit it can stay empty and not changed.

I have this model:

        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        [DisplayName("Re-enter Password")]
        [Compare("Password", ErrorMessage = "The password and confirmation do not match.")]
        public string PasswordControl { get; set; }

Enought vould be disable required on password on edit.

Upvotes: 0

Views: 259

Answers (1)

Chris Li
Chris Li

Reputation: 3725

AFAIK, there are two ways, either will work.

  1. Use different model for edit and insert. I prefer and use this one in my application. It's easy and future proof(Edit and insert models and rules may be quite different).

  2. Customize a ValidationAttribute and override IsValid method. Use some context such as IsEdit field of your model. It can be used since MVC3. See the "Model Validation Improvements" part of this article http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-preview-1.aspx

Upvotes: 1

Related Questions