MaxValueAttribute.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System;
  2. using System.ComponentModel.DataAnnotations;
  3. namespace Masuit.Tools.Core.Validator;
  4. /// <summary>
  5. /// 最大值校验
  6. /// </summary>
  7. public class MaxValueAttribute : ValidationAttribute
  8. {
  9. private double MaxValue { get; }
  10. /// <summary>
  11. /// 最大值
  12. /// </summary>
  13. /// <param name="value"></param>
  14. public MaxValueAttribute(double value)
  15. {
  16. MaxValue = value;
  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)
  26. {
  27. return true;
  28. }
  29. var input = Convert.ToDouble(value);
  30. return input <= MaxValue;
  31. }
  32. /// <summary>Applies formatting to an error message, based on the data field where the error occurred.</summary>
  33. /// <param name="name">The name to include in the formatted message.</param>
  34. /// <returns>An instance of the formatted error message.</returns>
  35. public override string FormatErrorMessage(string name)
  36. {
  37. return base.FormatErrorMessage(name);
  38. }
  39. }