ComplexPassword.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. using System.ComponentModel.DataAnnotations;
  2. using System.Text.RegularExpressions;
  3. namespace Masuit.Tools.Core.Validator
  4. {
  5. /// <summary>
  6. /// 强密码验证
  7. /// </summary>
  8. public class ComplexPassword : ValidationAttribute
  9. {
  10. /// <summary>
  11. /// 校验密码强度
  12. /// </summary>
  13. /// <param name="value"></param>
  14. /// <returns></returns>
  15. public override bool IsValid(object value)
  16. {
  17. string pwd = value as string;
  18. if (pwd.Length <= 6)
  19. {
  20. ErrorMessage = "密码过短,至少需要6个字符!";
  21. return false;
  22. }
  23. var regex = new Regex(@"(?=.*[0-9]) #必须包含数字
  24. (?=.*[a-zA-Z]) #必须包含小写或大写字母
  25. (?=([\x21-\x7e]+)[^a-zA-Z0-9]) #必须包含特殊符号
  26. .{6,30} #至少6个字符,最多30个字符
  27. ", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);
  28. if (regex.Match(pwd).Success)
  29. {
  30. return true;
  31. }
  32. ErrorMessage = "密码强度值不够,密码必须包含数字,必须包含小写或大写字母,必须包含至少一个特殊符号,至少6个字符,最多30个字符!";
  33. return false;
  34. }
  35. }
  36. }