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.

AbstractValidator.java 2.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. @VaadinApache2LicenseForJavaFiles@
  3. */
  4. package com.vaadin.data.validator;
  5. import com.vaadin.data.Validator;
  6. /**
  7. * Abstract {@link com.vaadin.data.Validator Validator} implementation that
  8. * provides a basic Validator implementation except the {@link #isValid(Object)}
  9. * method. Sub-classes need to implement the {@link #isValid(Object)} method.
  10. * <p>
  11. * To include the value that failed validation in the exception message you can
  12. * use "{0}" in the error message. This will be replaced with the failed value
  13. * (converted to string using {@link #toString()}) or "null" if the value is
  14. * null.
  15. * </p>
  16. * <p>
  17. * The default implementation of AbstractValidator does not support HTML in
  18. * error messages. To enable HTML support, override
  19. * {@link InvalidValueException#getHtmlMessage()} and throw such exceptions from
  20. * {@link #validate(Object)}.
  21. * </p>
  22. *
  23. * @author Vaadin Ltd.
  24. * @version
  25. * @VERSION@
  26. * @since 5.4
  27. */
  28. @SuppressWarnings("serial")
  29. public abstract class AbstractValidator implements Validator {
  30. /**
  31. * Error message that is included in an {@link InvalidValueException} if
  32. * such is thrown.
  33. */
  34. private String errorMessage;
  35. /**
  36. * Constructs a validator with the given error message.
  37. *
  38. * @param errorMessage
  39. * the message to be included in an {@link InvalidValueException}
  40. * (with "{0}" replaced by the value that failed validation).
  41. */
  42. public AbstractValidator(String errorMessage) {
  43. this.errorMessage = errorMessage;
  44. }
  45. public void validate(Object value) throws InvalidValueException {
  46. if (!isValid(value)) {
  47. String message = errorMessage.replace("{0}", String.valueOf(value));
  48. throw new InvalidValueException(message);
  49. }
  50. }
  51. /**
  52. * Returns the message to be included in the exception in case the value
  53. * does not validate.
  54. *
  55. * @return the error message provided in the constructor or using
  56. * {@link #setErrorMessage(String)}.
  57. */
  58. public String getErrorMessage() {
  59. return errorMessage;
  60. }
  61. /**
  62. * Sets the message to be included in the exception in case the value does
  63. * not validate. The exception message is typically shown to the end user.
  64. *
  65. * @param errorMessage
  66. * the error message. "{0}" is automatically replaced by the
  67. * value that did not validate.
  68. */
  69. public void setErrorMessage(String errorMessage) {
  70. this.errorMessage = errorMessage;
  71. }
  72. }