IsPhoneAttribute.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. /// <summary>
  15. ///
  16. /// </summary>
  17. /// <param name="customMessage">自定义错误消息</param>
  18. public IsPhoneAttribute(string customMessage = null)
  19. {
  20. _customMessage = customMessage;
  21. }
  22. /// <summary>
  23. /// 验证手机号码是否合法
  24. /// </summary>
  25. /// <param name="value"></param>
  26. /// <returns></returns>
  27. public override bool IsValid(object value)
  28. {
  29. if (AllowEmpty)
  30. {
  31. switch (value)
  32. {
  33. case null:
  34. case string s when string.IsNullOrEmpty(s):
  35. return true;
  36. }
  37. }
  38. if (value is null)
  39. {
  40. ErrorMessage = _customMessage ?? "手机号码不能为空";
  41. return false;
  42. }
  43. string phone = value as string;
  44. if (phone.MatchPhoneNumber())
  45. {
  46. return true;
  47. }
  48. ErrorMessage = _customMessage ?? "手机号码格式不正确,请输入有效的大陆11位手机号码!";
  49. return false;
  50. }
  51. }
  52. }