/** * Constructs a {@link RegexValidator} which validates a string based on a {@link Pattern} * * @param regex the regular expression which should be used to validate an input string * @return a {@link RegexValidator} which validates a string based on a {@link Pattern} */ public static RegexValidator of(String regex) { return new RegexValidator(regex, "Value \"{0}\" does not match regex {1}"); }
@Test void testRegexValidator() { SoftAssertions.assertSoftly(softly -> { softly.assertThatCode(() -> RegexValidator.of("foo").assertValid("foo")).doesNotThrowAnyException(); // checking for nullness is not the responsibility of the validator, but it must be null safe softly.assertThatCode(() -> RegexValidator.of("foo").assertValid(null)).doesNotThrowAnyException(); softly.assertThatCode(() -> RegexValidator.of("foo").assertValid("bar")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Value \"bar\" does not match regex foo"); softly.assertThatCode(() -> RegexValidator.of("foo", "{0} is not {1}").assertValid("bar")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("bar is not foo"); }); } }
/** * Constructs a {@link RegexValidator} which validates a string based on a {@link Pattern} * * @param regex the regular expression which should be used to validate an input string * @param errorMessagePattern a error message format pattern. The placeholder {@code {0}} contains the actual value, * while the placeholder {@code {1}} represents the regex. * @return a {@link RegexValidator} which validates a string based on a {@link Pattern} */ public static RegexValidator of(String regex, String errorMessagePattern) { return new RegexValidator(regex, errorMessagePattern); }