Tuesday, 3 April 2012

Asp.net mvc 3 DataAnnotation using IValidatableObject for multiple properties.

If you have a scenario in which you want to base a validation on multiple business logics on multiple properties then you should consider using IValidatableObject. One of the advantages is that you can use the properties attributes directly which open door to a lot of validation possibilities. It will only be called when there are no individual properties error. It doesn't support clientside validation. Below is the simple code that will give you insight of how this all works.

    public class User : IValidatableObject
    {
        [Key]
        public string UserId { get; set; }
        [Required]
        public string UserName { get; set; }
        [Required]
        public string Password { get; set; }
        [Compare("Password")]
        public string ConfirmPassword { get; set; }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            List<ValidationResult> err = new List<ValidationResult>();
            if(UserName.Equals(Password))
            {
                yield return new ValidationResult("UserName and password cannot be equal", new[] { "UserName" });
            }
        }
    }

No comments:

Post a Comment