Skip to content

Commit d5f35d5

Browse files
committed
feat: Validate string format 'byte'
1 parent 12fe5fd commit d5f35d5

2 files changed

Lines changed: 25 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
@@ -27,6 +27,7 @@
2727
import java.time.OffsetDateTime;
2828
import java.time.format.DateTimeParseException;
2929
import java.util.ArrayList;
30+
import java.util.Base64;
3031
import java.util.HashSet;
3132
import java.util.List;
3233
import java.util.Map;
@@ -86,7 +87,8 @@ private record FormatCheck(Predicate<String> isValid, String message) {}
8687
new FormatCheck(s -> HOSTNAME.matcher(s).matches(), "not a valid hostname")),
8788
Map.entry("ipv4", new FormatCheck(s -> IPV4.matcher(s).matches(), "not a valid ipv4")),
8889
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")));
90+
Map.entry("regex", new FormatCheck(DefaultValidator::isRegex, "not a valid regex")),
91+
Map.entry("byte", new FormatCheck(DefaultValidator::isByte, "not valid base64")));
9092

9193
private final Function<String, Schema> refResolver;
9294
private final ConcurrentMap<String, Pattern> compiledPatterns = new ConcurrentHashMap<>();
@@ -211,6 +213,15 @@ private static boolean isRegex(String s) {
211213
}
212214
}
213215

216+
private static boolean isByte(String s) {
217+
try {
218+
Base64.getDecoder().decode(s);
219+
return true;
220+
} catch (IllegalArgumentException _) {
221+
return false;
222+
}
223+
}
224+
214225
private static boolean isUriReference(String s) {
215226
try {
216227
new URI(s);

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,19 @@ void stringFormatRegex() {
197197
.isEqualTo("format");
198198
}
199199

200+
@Test
201+
void stringFormatByte() {
202+
StringSchema s = new StringSchema(Set.of(TypeName.STRING), null, null, null, "byte", null);
203+
assertThatCode(() -> v.validate("aGVsbG8=", s, "/v")).doesNotThrowAnyException();
204+
assertThatCode(() -> v.validate("", s, "/v")).doesNotThrowAnyException();
205+
assertThatThrownBy(() -> v.validate("not base64!!", s, "/v"))
206+
.extracting(t -> ((ValidationException) t).error().keyword())
207+
.isEqualTo("format");
208+
assertThatThrownBy(() -> v.validate("a===", s, "/v"))
209+
.extracting(t -> ((ValidationException) t).error().keyword())
210+
.isEqualTo("format");
211+
}
212+
200213
@Test
201214
void stringRejectsNonString() {
202215
StringSchema s = new StringSchema(Set.of(TypeName.STRING), null, null, null, null, null);

0 commit comments

Comments
 (0)