MaxValueAttribute.cs 1.3 KB

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