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.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. @VaadinApache2LicenseForJavaFiles@
  3. */
  4. package com.vaadin.data.validator;
  5. import com.vaadin.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 Vaadin Ltd.
  11. * @since 3.0
  12. */
  13. @SuppressWarnings("serial")
  14. public class NullValidator implements Validator {
  15. private boolean onlyNullAllowed;
  16. private String errorMessage;
  17. /**
  18. * Creates a new NullValidator.
  19. *
  20. * @param errorMessage
  21. * the error message to display on invalidation.
  22. * @param onlyNullAllowed
  23. * Are only nulls allowed?
  24. */
  25. public NullValidator(String errorMessage, boolean onlyNullAllowed) {
  26. setErrorMessage(errorMessage);
  27. setNullAllowed(onlyNullAllowed);
  28. }
  29. /**
  30. * Validates the data given in value.
  31. *
  32. * @param value
  33. * the value to validate.
  34. * @throws Validator.InvalidValueException
  35. * if the value was invalid.
  36. */
  37. @Override
  38. public void validate(Object value) throws Validator.InvalidValueException {
  39. if ((onlyNullAllowed && value != null)
  40. || (!onlyNullAllowed && value == null)) {
  41. throw new Validator.InvalidValueException(errorMessage);
  42. }
  43. }
  44. /**
  45. * Returns <code>true</code> if nulls are allowed otherwise
  46. * <code>false</code>.
  47. */
  48. public final boolean isNullAllowed() {
  49. return onlyNullAllowed;
  50. }
  51. /**
  52. * Sets if nulls (and only nulls) are to be allowed.
  53. *
  54. * @param onlyNullAllowed
  55. * If true, only nulls are allowed. If false only non-nulls are
  56. * allowed. Do we allow nulls?
  57. */
  58. public void setNullAllowed(boolean onlyNullAllowed) {
  59. this.onlyNullAllowed = onlyNullAllowed;
  60. }
  61. /**
  62. * Gets the error message that is displayed in case the value is invalid.
  63. *
  64. * @return the Error Message.
  65. */
  66. public String getErrorMessage() {
  67. return errorMessage;
  68. }
  69. /**
  70. * Sets the error message to be displayed on invalid value.
  71. *
  72. * @param errorMessage
  73. * the Error Message to set.
  74. */
  75. public void setErrorMessage(String errorMessage) {
  76. this.errorMessage = errorMessage;
  77. }
  78. }