IsEmailAttribute.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using Masuit.Tools.Config;
  2. using System.ComponentModel.DataAnnotations;
  3. using System.Linq;
  4. using System.Text.RegularExpressions;
  5. namespace Masuit.Tools.Core.Validator
  6. {
  7. /// <summary>
  8. /// 邮箱校验
  9. /// </summary>
  10. public class IsEmailAttribute : ValidationAttribute
  11. {
  12. private readonly bool _valid;
  13. /// <summary>
  14. /// 域白名单
  15. /// </summary>
  16. private string WhiteList { get; }
  17. /// <summary>
  18. /// 域黑名单
  19. /// </summary>
  20. private string BlockList { get; }
  21. /// <summary>
  22. /// 可在配置文件AppSetting节中添加EmailDomainWhiteList配置邮箱域名白名单,EmailDomainBlockList配置邮箱域名黑名单,逗号分隔,每个单独的元素支持正则表达式
  23. /// </summary>
  24. /// <param name="valid">是否检查邮箱的有效性</param>
  25. public IsEmailAttribute(bool valid = true)
  26. {
  27. WhiteList = Regex.Replace(ConfigHelper.GetConfigOrDefault("EmailDomainWhiteList"), @"(\w)\.([a-z]+),?", @"$1\.$2!").Trim('!');
  28. BlockList = Regex.Replace(ConfigHelper.GetConfigOrDefault("EmailDomainBlockList"), @"(\w)\.([a-z]+),?", @"$1\.$2!").Trim('!');
  29. _valid = valid;
  30. }
  31. /// <summary>
  32. /// 邮箱校验
  33. /// </summary>
  34. /// <param name="value"></param>
  35. /// <returns></returns>
  36. public override bool IsValid(object value)
  37. {
  38. if (value == null)
  39. {
  40. ErrorMessage = "邮箱不能为空!";
  41. return false;
  42. }
  43. var email = (string)value;
  44. if (email.Length < 7)
  45. {
  46. ErrorMessage = "您输入的邮箱格式不正确!";
  47. return false;
  48. }
  49. if (email.Length > 256)
  50. {
  51. ErrorMessage = "您输入的邮箱无效,请使用真实有效的邮箱地址!";
  52. return false;
  53. }
  54. if (!string.IsNullOrEmpty(BlockList) && BlockList.Split('!').Any(item => Regex.IsMatch(email, item)))
  55. {
  56. ErrorMessage = "您输入的邮箱无效,请使用真实有效的邮箱地址!";
  57. return false;
  58. }
  59. if (!string.IsNullOrEmpty(WhiteList) && WhiteList.Split('!').Any(item => Regex.IsMatch(email, item)))
  60. {
  61. return true;
  62. }
  63. if (email.MatchEmail(_valid).isMatch)
  64. {
  65. return true;
  66. }
  67. ErrorMessage = "您输入的邮箱格式不正确!";
  68. return false;
  69. }
  70. }
  71. }