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.

NullValidator.java 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /*
  2. @ITMillApache2LicenseForJavaFiles@
  3. */
  4. package com.itmill.toolkit.data.validator;
  5. import com.itmill.toolkit.data.Validator;
  6. /**
  7. * This validator is used for validating properties that do or do not allow null
  8. * values. By default, nulls are not allowed.
  9. *
  10. * @author IT Mill Ltd.
  11. * @version
  12. * @VERSION@
  13. * @since 3.0
  14. */
  15. public class NullValidator implements Validator {
  16. private boolean allowNull;
  17. private String errorMessage;
  18. /**
  19. * Creates a new NullValidator.
  20. *
  21. * @param errorMessage
  22. * the error message to display on invalidation.
  23. * @param allowNull
  24. * Are nulls allowed?
  25. */
  26. public NullValidator(String errorMessage, boolean allowNull) {
  27. setErrorMessage(errorMessage);
  28. setNullAllowed(allowNull);
  29. }
  30. /**
  31. * Validates the data given in value.
  32. *
  33. * @param value
  34. * the value to validate.
  35. * @throws Validator.InvalidValueException
  36. * if the value was invalid.
  37. */
  38. public void validate(Object value) throws Validator.InvalidValueException {
  39. if ((allowNull && value != null) || (!allowNull && value == null)) {
  40. throw new Validator.InvalidValueException(errorMessage);
  41. }
  42. }
  43. /**
  44. * Tests if the given value is valid.
  45. *
  46. * @param value
  47. * the value to validate.
  48. * @returns <code>true</code> for valid value, otherwise
  49. * <code>false</code>.
  50. */
  51. public boolean isValid(Object value) {
  52. return allowNull ? value == null : value != null;
  53. }
  54. /**
  55. * Returns <code>true</code> if nulls are allowed otherwise
  56. * <code>false</code>.
  57. */
  58. public final boolean isNullAllowed() {
  59. return allowNull;
  60. }
  61. /**
  62. * Sets if nulls are to be allowed.
  63. *
  64. * @param allowNull
  65. * If true, only nulls are allowed. If false only non-nulls
  66. * are allowed. Do we allow nulls?
  67. */
  68. public void setNullAllowed(boolean allowNull) {
  69. this.allowNull = allowNull;
  70. }
  71. /**
  72. * Gets the error message that is displayed in case the value is invalid.
  73. *
  74. * @return the Error Message.
  75. */
  76. public String getErrorMessage() {
  77. return errorMessage;
  78. }
  79. /**
  80. * Sets the error message to be displayed on invalid value.
  81. *
  82. * @param errorMessage
  83. * the Error Message to set.
  84. */
  85. public void setErrorMessage(String errorMessage) {
  86. this.errorMessage = errorMessage;
  87. }
  88. }