You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

IntegerValidator.java 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package com.dmdirc.util.validators;
  7. /**
  8. * Validates that a number is within certain bounds.
  9. */
  10. public class IntegerValidator implements Validator<Integer> {
  11. /**
  12. * The minimum value for this number.
  13. */
  14. protected final int min;
  15. /**
  16. * The maximum value for this number.
  17. */
  18. protected final int max;
  19. /**
  20. * Creates a new numerical validator with the specified bounds.
  21. *
  22. * @param min The minimum value for the number, or -1 for unlimited.
  23. * @param max The maximum value for the number, or -1 for unlimited.
  24. */
  25. public IntegerValidator(final int min, final int max) {
  26. this.max = max == -1 ? Integer.MAX_VALUE : max;
  27. this.min = min == -1 ? Integer.MIN_VALUE : min;
  28. if (this.min > this.max) {
  29. throw new IllegalArgumentException("min must be less than max.");
  30. }
  31. }
  32. /**
  33. * Retrieves the maximum value that this validator will allow.
  34. *
  35. * @return This validator's maximum value
  36. */
  37. public int getMax() {
  38. return max;
  39. }
  40. /**
  41. * Retrieves the minimum value that this validator will allow.
  42. *
  43. * @return This validator's minimum value
  44. */
  45. public int getMin() {
  46. return min;
  47. }
  48. @Override
  49. public ValidationResponse validate(final Integer object) {
  50. if (object < min) {
  51. return new ValidationResponse("Must be at least " + min);
  52. } else if (object > max) {
  53. return new ValidationResponse("Must be at most " + max);
  54. } else {
  55. return new ValidationResponse();
  56. }
  57. }
  58. }