Tutorial :Disable validation on certain fields



Question:

I've got a ViewModel for adding a user with properties: Email, Password, ConfirmPassword with Required attribute on all properties. When editing a user I want the Password and ConfirmPassword properties not to be required.

Is there a way to disable validation for certain properties in different controller actions, or is it just best to create a seperate EditViewModel?


Solution:1

I like to break it down and make a base model with all the common data and inhierit for each view:

class UserBaseModel  {      int ID { get; set; }        [Required]      string Name { get; set; }               [Required]      string Email { get; set; }                     // etc...  }    class UserNewModel : UserBaseModel  {      [Required]      string Password { get; set; }        [Required]      string ConfirmPassword { get; set; }  }    class UserEditModel : UserBaseModel  {      string Password { get; set; }      string ConfirmPassword { get; set; }  }  

Interested to know if there is a better way as well although this way seems very clean an flexible.


Solution:2

You could write a custom attribute that can test a condition and either allow an empty field or not allow it.

The below is a simple demo i put together for the guys here. You'll need to modify to suit your purposes/

    using System.ComponentModel.DataAnnotations;        namespace CustomAttributes        {        [System.AttributeUsage(System.AttributeTargets.Property)]        public class MinimumLength : ValidationAttribute        {          public int Length { get; set; }          public MinimumLength()          {          }            public override bool IsValid(object obj)          {              string value = (string)obj;              if (string.IsNullOrEmpty(value)) return false;              if (value.Length < this.Length)                  return false;              else                  return true;          }      }  }  

Model;

using CustomAttributes;    namespace Models  {      public class Application      {          [MinimumLength(Length=20)]          public string name { get; set; }      }  }  

Controller

 [AcceptVerbs(HttpVerbs.Post)]  public ActionResult Index(Application b)  {      ViewData["Message"] = "Welcome to ASP.NET MVC!";        if (ModelState.IsValid)      {          return RedirectToAction("MyOtherAction");      }      return View(b);  }    enter code here  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »