IsPhoneAttribute.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System.ComponentModel.DataAnnotations;
  2. namespace Masuit.Tools.Core.Validator
  3. {
  4. /// <summary>
  5. /// 验证手机号码是否合法
  6. /// </summary>
  7. public class IsPhoneAttribute : ValidationAttribute
  8. {
  9. /// <summary>
  10. /// 是否允许为空
  11. /// </summary>
  12. public bool AllowEmpty { get; set; }
  13. private readonly string _customMessage;
  14. public IsPhoneAttribute()
  15. {
  16. _customMessage = ErrorMessage;
  17. }
  18. /// <summary>
  19. /// 验证手机号码是否合法
  20. /// </summary>
  21. /// <param name="value"></param>
  22. /// <returns></returns>
  23. public override bool IsValid(object value)
  24. {
  25. if (value is null && !AllowEmpty)
  26. {
  27. ErrorMessage = _customMessage ?? "手机号码不能为空";
  28. return false;
  29. }
  30. string phone = value as string;
  31. if (phone.MatchPhoneNumber())
  32. {
  33. return true;
  34. }
  35. ErrorMessage = _customMessage ?? "手机号码格式不正确,请输入有效的大陆11位手机号码!";
  36. return false;
  37. }
  38. }
  39. }