Skip to content

Commit 6a23811

Browse files
committed
feat: Validate string format 'hostname'
1 parent 47f5985 commit 6a23811

2 files changed

Lines changed: 22 additions & 1 deletion

File tree

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

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,11 @@ 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 HOSTNAME =
51+
Pattern.compile(
52+
"^(?=.{1,253}$)([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)"
53+
+ "(\\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$");
54+
5055
private static final Map<String, FormatCheck> FORMAT_CHECKS =
5156
Map.ofEntries(
5257
Map.entry("uuid", new FormatCheck(DefaultValidator::isUuid, "not a valid uuid")),
@@ -57,7 +62,10 @@ private record FormatCheck(Predicate<String> isValid, String message) {}
5762
Map.entry("uri", new FormatCheck(DefaultValidator::isUri, "not a valid uri")),
5863
Map.entry(
5964
"uri-reference",
60-
new FormatCheck(DefaultValidator::isUriReference, "not a valid uri-reference")));
65+
new FormatCheck(DefaultValidator::isUriReference, "not a valid uri-reference")),
66+
Map.entry(
67+
"hostname",
68+
new FormatCheck(s -> HOSTNAME.matcher(s).matches(), "not a valid hostname")));
6169

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

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,19 @@ void stringFormatUriReference() {
103103
.isEqualTo("format");
104104
}
105105

106+
@Test
107+
void stringFormatHostname() {
108+
StringSchema s = new StringSchema(Set.of(TypeName.STRING), null, null, null, "hostname", null);
109+
assertThatCode(() -> v.validate("example.com", s, "/v")).doesNotThrowAnyException();
110+
assertThatCode(() -> v.validate("a.b.c.example", s, "/v")).doesNotThrowAnyException();
111+
assertThatThrownBy(() -> v.validate("-leading-hyphen.com", s, "/v"))
112+
.extracting(t -> ((ValidationException) t).error().keyword())
113+
.isEqualTo("format");
114+
assertThatThrownBy(() -> v.validate("invalid host name", s, "/v"))
115+
.extracting(t -> ((ValidationException) t).error().keyword())
116+
.isEqualTo("format");
117+
}
118+
106119
@Test
107120
void integerWithMinMax() {
108121
IntegerSchema s =

0 commit comments

Comments
 (0)