Thursday, March 6, 2014

How to trigger validation on Data annotation attributes in C#?

Name space: System.ComponentModel.DataAnnotations
var validationResults = new List();
            var myObject = new LoginViewModel();
            var validateContext = new ValidationContext(myObject, null, null);
            var isValid =  Validator.TryValidateObject(myObject, validateContext,validationResults);

    public class LoginViewModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [Display(Name = "Remember me?")]
        public bool RememberMe { get; set; }
    }

No comments:

Post a Comment