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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /*
  2. @VaadinApache2LicenseForJavaFiles@
  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 Vaadin Ltd.
  21. * @since 5.4
  22. */
  23. @SuppressWarnings("serial")
  24. public class RegexpValidator extends AbstractStringValidator {
  25. private Pattern pattern;
  26. private boolean complete;
  27. private transient Matcher matcher = null;
  28. /**
  29. * Creates a validator for checking that the regular expression matches the
  30. * complete string to validate.
  31. *
  32. * @param regexp
  33. * a Java regular expression
  34. * @param errorMessage
  35. * the message to display in case the value does not validate.
  36. */
  37. public RegexpValidator(String regexp, String errorMessage) {
  38. this(regexp, true, errorMessage);
  39. }
  40. /**
  41. * Creates a validator for checking that the regular expression matches the
  42. * string to validate.
  43. *
  44. * @param regexp
  45. * a Java regular expression
  46. * @param complete
  47. * true to use check for a complete match, false to look for a
  48. * matching substring
  49. * @param errorMessage
  50. * the message to display in case the value does not validate.
  51. */
  52. public RegexpValidator(String regexp, boolean complete, String errorMessage) {
  53. super(errorMessage);
  54. pattern = Pattern.compile(regexp);
  55. this.complete = complete;
  56. }
  57. /*
  58. * (non-Javadoc)
  59. *
  60. * @see
  61. * com.vaadin.data.validator.AbstractValidator#isValidValue(java.lang.Object
  62. * )
  63. */
  64. @Override
  65. protected boolean isValidValue(String value) {
  66. if (complete) {
  67. return getMatcher(value).matches();
  68. } else {
  69. return getMatcher(value).find();
  70. }
  71. }
  72. /**
  73. * Get a new or reused matcher for the pattern
  74. *
  75. * @param value
  76. * the string to find matches in
  77. * @return Matcher for the string
  78. */
  79. private Matcher getMatcher(String value) {
  80. if (matcher == null) {
  81. matcher = pattern.matcher(value);
  82. } else {
  83. matcher.reset(value);
  84. }
  85. return matcher;
  86. }
  87. }