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

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