Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

RegexpValidator.java 2.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. * @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. /*
  60. * (non-Javadoc)
  61. *
  62. * @see
  63. * com.vaadin.data.validator.AbstractValidator#isValidValue(java.lang.Object
  64. * )
  65. */
  66. @Override
  67. protected boolean isValidValue(String value) {
  68. if (complete) {
  69. return getMatcher(value).matches();
  70. } else {
  71. return getMatcher(value).find();
  72. }
  73. }
  74. /**
  75. * Get a new or reused matcher for the pattern
  76. *
  77. * @param value
  78. * the string to find matches in
  79. * @return Matcher for the string
  80. */
  81. private Matcher getMatcher(String value) {
  82. if (matcher == null) {
  83. matcher = pattern.matcher(value);
  84. } else {
  85. matcher.reset(value);
  86. }
  87. return matcher;
  88. }
  89. }