Skip to content

Commit 4f09f16

Browse files
committed
feat: Validate string format 'ipv4'
1 parent 6a23811 commit 4f09f16

2 files changed

Lines changed: 19 additions & 1 deletion

File tree

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

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,9 @@ private record FormatCheck(Predicate<String> isValid, String message) {}
4747

4848
private static final Pattern EMAIL = Pattern.compile("^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$");
4949

50+
private static final Pattern IPV4 =
51+
Pattern.compile("^((25[0-5]|2[0-4]\\d|1?\\d?\\d)\\.){3}(25[0-5]|2[0-4]\\d|1?\\d?\\d)$");
52+
5053
private static final Pattern HOSTNAME =
5154
Pattern.compile(
5255
"^(?=.{1,253}$)([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)"
@@ -65,7 +68,8 @@ private record FormatCheck(Predicate<String> isValid, String message) {}
6568
new FormatCheck(DefaultValidator::isUriReference, "not a valid uri-reference")),
6669
Map.entry(
6770
"hostname",
68-
new FormatCheck(s -> HOSTNAME.matcher(s).matches(), "not a valid hostname")));
71+
new FormatCheck(s -> HOSTNAME.matcher(s).matches(), "not a valid hostname")),
72+
Map.entry("ipv4", new FormatCheck(s -> IPV4.matcher(s).matches(), "not a valid ipv4")));
6973

7074
private final Function<String, Schema> refResolver;
7175
private final ConcurrentMap<String, Pattern> compiledPatterns = new ConcurrentHashMap<>();

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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,20 @@ void stringFormatHostname() {
116116
.isEqualTo("format");
117117
}
118118

119+
@Test
120+
void stringFormatIpv4() {
121+
StringSchema s = new StringSchema(Set.of(TypeName.STRING), null, null, null, "ipv4", null);
122+
assertThatCode(() -> v.validate("192.168.0.1", s, "/v")).doesNotThrowAnyException();
123+
assertThatCode(() -> v.validate("0.0.0.0", s, "/v")).doesNotThrowAnyException();
124+
assertThatCode(() -> v.validate("255.255.255.255", s, "/v")).doesNotThrowAnyException();
125+
assertThatThrownBy(() -> v.validate("256.0.0.1", s, "/v"))
126+
.extracting(t -> ((ValidationException) t).error().keyword())
127+
.isEqualTo("format");
128+
assertThatThrownBy(() -> v.validate("1.2.3", s, "/v"))
129+
.extracting(t -> ((ValidationException) t).error().keyword())
130+
.isEqualTo("format");
131+
}
132+
119133
@Test
120134
void integerWithMinMax() {
121135
IntegerSchema s =

0 commit comments

Comments
 (0)