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

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