Haneef Puttur

Easy Password validator for MVC C#

If you are developing an application in MVC C# use this code in your password model to make easy validation

  [Required]
        [DataType(DataType.Password)]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 8)]
        [Display(Name = "Password")]
        [RegularExpression("^((?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])|(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[^a-zA-Z0-9])|(?=.*?[A-Z])(?=.*?[0-9])(?=.*?[^a-zA-Z0-9])|(?=.*?[a-z])(?=.*?[0-9])(?=.*?[^a-zA-Z0-9])).{8,}$", ErrorMessage = "Passwords must be at least 8 characters and contain at 3 of 4 of the following: upper case (A-Z), lower case (a-z), number (0-9) and special character (e.g. !@#$%^&*)")]
        public string Password { get; set; }

This will impose following password policy

Passwords must be at least 8 characters

And

Satisfy any of  3 from 4 of the following:

  1. upper case (A-Z),
  2. lower case (a-z),
  3. number (0-9)
  4. special character (e.g. !@#$%^&*)
Exit mobile version