I have a custom data validation attribute that I created to make sure that the user input passwords are the same, but IsValid is never called.
User attribute:
public class IsSameAsAttribute : ValidationAttribute { public String TargetProperty { get; set; } private readonly object _typeId = new object(); public IsSameAsAttribute(string targetProperty) { TargetProperty = targetProperty; } public override bool IsValid(object value) { return false;
The data model applies to:
public class RegistrationData { [Required(ErrorMessage = "First Name Required")] [StringLength(100, ErrorMessage = "First Name must be 100 characters or less.")] public String FirstName { get; set;} [Required(ErrorMessage = "Last Name Required")] [StringLength(100, ErrorMessage = "Last Name must be 100 characters or less.")] public String LastName { get; set; } [Required(ErrorMessage = "Email is Required")] [StringLength(200, ErrorMessage = "Email must be 200 characters or less.")] [RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Valid Email Address is required.")] public String Email { get; set; } [Required(ErrorMessage = "Password is required")] public String Password { get; set; } [IsSameAs("Password")] public String PasswordRepeat { get; set; } [Required(ErrorMessage = "Division is required")] public String Division { get; set; } }
And the controller from which it is called:
[HttpPost] public ActionResult ValidationDemo(RegistrationData model) { if (ModelState.IsValid) { return Redirect("/"); } return View(model); }
All checks out of the box work correctly, it's just my custom one that is not called. When debugging, I find that it is created when the constructor is called, but the set of interrupts never gets to IsValid.
What is happening and how to fix it?
UPDATE
All I mumbled, and if I call TryUpdateModel (model) in my controller, it finally calls IsValid. Thus, this means that my user attribute is not getting "registered" so that checks are performed in MVC 2. Is there a way to solve this problem?
[HttpPost] public ActionResult ValidationDemo(RegistrationData model) { TryValidateModel(model); // <--- *** Added this line and it "works" if (ModelState.IsValid) { return Redirect("/"); } return View(model); }
Jack
source share