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.

RegexpValidator.java 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. @ITMillApache2LicenseForJavaFiles@
  3. */
  4. package com.vaadin.data.validator;
  5. import java.util.regex.Matcher;
  6. import java.util.regex.Pattern;
  7. /**
  8. * String validator comparing the string against a Java regular expression. Both
  9. * complete matches and substring matches are supported.
  10. *
  11. * <p>
  12. * For the Java regular expression syntax, see
  13. * {@link java.util.regex.Pattern#sum}
  14. * </p>
  15. * <p>
  16. * See {@link com.vaadin.data.validator.AbstractStringValidator} for more
  17. * information.
  18. * </p>
  19. *
  20. * @author IT Mill Ltd.
  21. * @version
  22. * @VERSION@
  23. * @since 5.4
  24. */
  25. @SuppressWarnings("serial")
  26. public class RegexpValidator extends AbstractStringValidator {
  27. private Pattern pattern;
  28. private boolean complete;
  29. private transient Matcher matcher = null;
  30. /**
  31. * Creates a validator for checking that the regular expression matches the
  32. * complete string to validate.
  33. *
  34. * @param regexp
  35. * a Java regular expression
  36. * @param errorMessage
  37. * the message to display in case the value does not validate.
  38. */
  39. public RegexpValidator(String regexp, String errorMessage) {
  40. this(regexp, true, errorMessage);
  41. }
  42. /**
  43. * Creates a validator for checking that the regular expression matches the
  44. * string to validate.
  45. *
  46. * @param regexp
  47. * a Java regular expression
  48. * @param complete
  49. * true to use check for a complete match, false to look for a
  50. * matching substring
  51. * @param errorMessage
  52. * the message to display in case the value does not validate.
  53. */
  54. public RegexpValidator(String regexp, boolean complete, String errorMessage) {
  55. super(errorMessage);
  56. pattern = Pattern.compile(regexp);
  57. this.complete = complete;
  58. }
  59. @Override
  60. protected boolean isValidString(String value) {
  61. if (complete) {
  62. return getMatcher(value).matches();
  63. } else {
  64. return getMatcher(value).find();
  65. }
  66. }
  67. /**
  68. * Get a new or reused matcher for the pattern
  69. *
  70. * @param value
  71. * the string to find matches in
  72. * @return Matcher for the string
  73. */
  74. private Matcher getMatcher(String value) {
  75. if (matcher == null) {
  76. matcher = pattern.matcher(value);
  77. } else {
  78. matcher.reset(value);
  79. }
  80. return matcher;
  81. }
  82. }