Skip to content

Commit 12fe5fd

Browse files
committed
feat: Validate string format 'regex'
1 parent c1c9068 commit 12fe5fd

2 files changed

Lines changed: 22 additions & 1 deletion

File tree

src/main/java/com/retailsvc/http/validate/DefaultValidator.java

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
import java.util.function.Function;
3939
import java.util.function.Predicate;
4040
import java.util.regex.Pattern;
41+
import java.util.regex.PatternSyntaxException;
4142

4243
public final class DefaultValidator implements Validator {
4344

@@ -84,7 +85,8 @@ private record FormatCheck(Predicate<String> isValid, String message) {}
8485
"hostname",
8586
new FormatCheck(s -> HOSTNAME.matcher(s).matches(), "not a valid hostname")),
8687
Map.entry("ipv4", new FormatCheck(s -> IPV4.matcher(s).matches(), "not a valid ipv4")),
87-
Map.entry("ipv6", new FormatCheck(s -> IPV6.matcher(s).matches(), "not a valid ipv6")));
88+
Map.entry("ipv6", new FormatCheck(s -> IPV6.matcher(s).matches(), "not a valid ipv6")),
89+
Map.entry("regex", new FormatCheck(DefaultValidator::isRegex, "not a valid regex")));
8890

8991
private final Function<String, Schema> refResolver;
9092
private final ConcurrentMap<String, Pattern> compiledPatterns = new ConcurrentHashMap<>();
@@ -200,6 +202,15 @@ private static boolean isUri(String s) {
200202
}
201203
}
202204

205+
private static boolean isRegex(String s) {
206+
try {
207+
Pattern.compile(s);
208+
return true;
209+
} catch (PatternSyntaxException _) {
210+
return false;
211+
}
212+
}
213+
203214
private static boolean isUriReference(String s) {
204215
try {
205216
new URI(s);

src/test/java/com/retailsvc/http/validate/StringIntegerNumberTest.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,16 @@ void numberAcceptsDoublesAndIntegers() {
187187
.isEqualTo("maximum");
188188
}
189189

190+
@Test
191+
void stringFormatRegex() {
192+
StringSchema s = new StringSchema(Set.of(TypeName.STRING), null, null, null, "regex", null);
193+
assertThatCode(() -> v.validate("^[a-z]+$", s, "/v")).doesNotThrowAnyException();
194+
assertThatCode(() -> v.validate("\\d{3}-\\d{4}", s, "/v")).doesNotThrowAnyException();
195+
assertThatThrownBy(() -> v.validate("[invalid", s, "/v"))
196+
.extracting(t -> ((ValidationException) t).error().keyword())
197+
.isEqualTo("format");
198+
}
199+
190200
@Test
191201
void stringRejectsNonString() {
192202
StringSchema s = new StringSchema(Set.of(TypeName.STRING), null, null, null, null, null);

0 commit comments

Comments
 (0)