ComplexPassword.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132
  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. public override bool IsValid(object value)
  11. {
  12. string pwd = value as string;
  13. if (pwd.Length <= 6)
  14. {
  15. ErrorMessage = "密码过短,至少需要6个字符!";
  16. return false;
  17. }
  18. var regex = new Regex(@"(?=.*[0-9]) #必须包含数字
  19. (?=.*[a-zA-Z]) #必须包含小写或大写字母
  20. (?=([\x21-\x7e]+)[^a-zA-Z0-9]) #必须包含特殊符号
  21. .{6,30} #至少6个字符,最多30个字符
  22. ", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);
  23. if (regex.Match(pwd).Success)
  24. {
  25. return true;
  26. }
  27. ErrorMessage = "密码强度值不够,密码必须包含数字,必须包含小写或大写字母,必须包含至少一个特殊符号,至少6个字符,最多30个字符!";
  28. return false;
  29. }
  30. }
  31. }