Scrivio Interview library
DesignAdvanced8 min read · updated 12 November 2026

You want to offer shared constraints such as @ValidCurrency, @ValidCountry and @ValidIban to all services. How would you design and maintain the library?

I would put @ValidCurrency, @ValidCountry and @ValidIban into one small library with a named owning team and semantic versions. Every constraint treats null as valid and says so in its documentation, takes its reference data from a reliable source that is refreshed on a schedule, reports its message through a shared bundle with stable codes, and is protected by unit tests plus a compatibility suite that runs on every upgrade.

Why this question is asked

When every service writes its own IBAN regex and its own list of currency codes, the same payment can be accepted by one service and rejected by the next. Clients then see different answers for the same input, and fixing a bug means changing twenty repositories. A shared constraints library solves that, but only if it is designed like a product: someone owns it, it changes in predictable ways, and services can trust an upgrade. Interviewers ask this question to see whether we think beyond writing one annotation and about how such code lives for years. In this answer, we will recap how a custom constraint is built, then go through ownership and versioning, the rule that null is valid, where reference data comes from, how messages are shared, and how we test each constraint and each upgrade.

1A Quick Recap of Custom Constraints

Jakarta Bean Validation lets us declare rules as annotations on fields and parameters. A custom constraint has two parts. The annotation itself carries @Constraint, which names the class that does the checking, and it must declare three attributes the specification requires: message, groups and payload. The checking class implements ConstraintValidator, whose isValid method receives the value and returns true or false.

Here is the shape of @ValidCurrency. Everything in the library follows the same pattern, so once a team has seen one constraint, it knows them all.

Java
@Documented
@Constraint(validatedBy = CurrencyCodeValidator.class)
@Target({ FIELD, METHOD, PARAMETER, TYPE_USE, ANNOTATION_TYPE })
@Retention(RUNTIME)
public @interface ValidCurrency {
String message() default "{com.example.validation.ValidCurrency.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class CurrencyCodeValidator implements ConstraintValidator<ValidCurrency, String> {
private static final Set<String> CODES = CurrencyData.isoCodes(); // loaded once
@Override
public boolean isValid(String value, ConstraintValidatorContext ctx) {
if (value == null) return true; // null is the job of @NotNull
return CODES.contains(value); // "EUR" -> true, "eur" -> false, "EURO" -> false
}
}

Notice that the validator holds its reference data in a static set that is loaded once. isValid runs for every request, so it must be cheap and must never call a network service.

2One Library, One Owner, Clear Versions

The first design decision is organisational. The library lives in one repository, for example com.example:validation-constraints, and one team owns it: it reviews changes, publishes releases and answers questions. Other teams contribute through pull requests, but the owner decides. It depends only on the jakarta.validation API, not on Hibernate Validator or Spring, so any service can use it with the provider it already has.

Versioning follows semantic versions, and the interesting part is deciding what counts as a breaking change. Adding a new constraint is a minor release. Making an existing constraint stricter, for example rejecting a currency code it used to accept, is a major release, because an input that passed yesterday will fail today and a client may break. We also publish the library in the company's dependency BOM, so a platform upgrade brings a tested combination of the library, Spring Boot and Hibernate Validator.

What a change to the library costs
ChangeVersion bumpWhy
Add @ValidPostcodeminornothing that passed before fails now
Refresh currency list with a new codeminoronly accepts more input
Reject a withdrawn currency codemajorinput that passed yesterday fails today
Change a message codemajorclients may match on the code
Fix a typo in the English messagepatchcodes and results are unchanged
Tightening a rule or renaming a code is breaking, even though the Java API did not change.

3Why Every Constraint Returns True for Null

In Bean Validation, each constraint checks one thing. Whether a value is required is a separate rule, expressed with @NotNull or @NotBlank. So the convention, followed by the built-in constraints such as @Email and @Pattern, is that a constraint treats null as valid. Our library follows the same rule and states it in the Javadoc of every annotation, because a team that assumes @ValidIban also rejects null will ship an endpoint that accepts empty payments.

Java
record Payment(@ValidCurrency String currency,
@NotNull @ValidIban String iban) {}
validator.validate(new Payment("EUR", "GB82WEST12345698765432")).size(); // 0
validator.validate(new Payment(null, "GB82WEST12345698765432")).size(); // 0: currency is optional here
validator.validate(new Payment("EUR", null)).size(); // 1: @NotNull fails, @ValidIban says nothing
validator.validate(new Payment("XXY", "GB82WEST12345698765432")).size(); // 1: unknown currency

The reason for this split is composition. The same @ValidCurrency works on an optional field and on a required one, and each violation has exactly one cause.

4Where the Reference Data Comes From

A currency or country constraint is only as good as its list, and a list typed by hand into the validator is never updated. For currencies, the JDK already ships the ISO 4217 table through java.util.Currency.getAvailableCurrencies(), and JDK update releases bring amendments to it. For countries, Locale.getISOCountries() returns the ISO 3166 two-letter codes. That is convenient, but it ties the data to the JDK version each service runs, so two services on different JDKs may disagree. Many teams therefore copy the official list into a versioned data file inside the library, so the list changes only when the library changes. IBAN validation has two parts: a structural check with the mod-97 checksum, which never changes, and a table of country prefixes and lengths from the IBAN registry, which does change a few times a year.

Java
static boolean ibanChecksumOk(String input) {
String s = input.replace(" ", "").toUpperCase(Locale.ROOT);
if (!s.matches("[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}")) return false;
String moved = s.substring(4) + s.substring(0, 4); // country and check digits go to the end
int rest = 0;
for (char c : moved.toCharArray()) {
int v = Character.isDigit(c) ? c - '0' : c - 'A' + 10; // A = 10 ... Z = 35
rest = (v > 9 ? rest * 100 + v : rest * 10 + v) % 97;
}
return rest == 1;
}
ibanChecksumOk("GB82 WEST 1234 5698 7654 32"); // true
ibanChecksumOk("GB82 WEST 1234 5698 7654 33"); // false: one digit changed

The length table and the currency file are the parts that age. A scheduled job compares our file with the published source each month and opens a pull request when it differs, and the library exposes its dataset version in a startup log line, so when two services disagree we can see which data each one runs. Note also that valid ISO codes are not the same as the currencies our business supports; that is a business rule for configuration or the service layer, not for @ValidCurrency.

5Messages Through a Shared Bundle With Codes

Every constraint's message attribute is a key in braces, such as {com.example.validation.ValidCurrency.message}, never a literal sentence. The library ships the default English text for these keys, and services can override or translate them. In Spring Boot 2.6 and later, the auto-configured validator resolves these keys through the application's MessageSource first, so a service can override a message in its own messages.properties.

One packaging trap: the provider's default bundle is called ValidationMessages, and when several jars contain a ValidationMessages.properties, normally only the first on the classpath is used. So the library ships its messages under a bundle name of its own and registers it with the MessageSource; check your provider version for its options.

The code matters more than the text. Spring turns each violation into codes built from the annotation name, such as ValidCurrency.payment.currency and ValidCurrency. Our shared error format exposes a stable code derived from that, for example invalid_currency, and clients match on the code, never on the English sentence.

6Testing Each Constraint and Every Upgrade

Each constraint has plain unit tests that build a validator with Validation.buildDefaultValidatorFactory() and run a table of known-good and known-bad values: real IBANs from several countries, IBANs with one wrong digit, lowercase currency codes, and null. When a bug report arrives, the failing value is added to the table first.

The second layer is a compatibility suite. The library is built against the Spring Boot and Hibernate Validator versions that services actually run, because a provider upgrade can change details such as message interpolation. Before a release, the same value tables run against the previous release, and every value whose result changed is listed in the changelog. That list is what lets a service owner upgrade with confidence.

7Follow-up questions

Should a constraint like @ValidIban call an external IBAN service?

No. A constraint runs on every request, often many times per request, and it should be fast, deterministic and side-effect free. A network call would make validation slow and turn a remote outage into a wall of 400 errors. Checks that need a remote service, such as whether an account exists, belong in the service layer, where we can handle timeouts and retries properly.

How do you roll out a stricter version of a constraint?

We release it as a new major version, describe exactly which inputs change in the changelog, and give the list of affected values to service owners. For risky changes we can first ship the stricter check in a report-only mode that logs what would fail, look at production logs for a few weeks, and only then make it enforcing.

8Conclusion

In this answer, we designed a shared constraints library. We saw how a custom constraint is built from an annotation and a ConstraintValidator, gave the library one owner and semantic versions in which tightening a rule counts as breaking, kept null valid so constraints compose with @NotNull, named a source and a refresh process for currency, country and IBAN data, shared messages through keys and stable codes, and protected every release with unit tests and a compatibility suite.

What to say in the interviewAbout 80 seconds aloud

Open with

I would build one library, owned by a platform team, that contains the shared constraints like @ValidCurrency, @ValidCountry and @ValidIban. It depends only on the Jakarta Validation API, so any service can use it, and it is released with semantic versions.

Then, if they want more

I treat making a rule stricter or renaming an error code as a breaking change, because input that passed yesterday would fail today. Every constraint follows the Bean Validation convention that null is valid, and the Javadoc says so, so teams combine it with @NotNull when the field is required.

For reference data, I name a source for each list: ISO currency and country codes kept in a versioned data file, and for IBANs the mod-97 checksum plus the registry's country lengths. A scheduled job checks those sources and opens a pull request when they change, and the library exposes its dataset version.

Messages are keys in a shared bundle, and the error format exposes a stable code that clients can match on.

Finally, each constraint has table-driven unit tests with real good and bad values, and the library runs a compatibility suite against the Boot and Hibernate Validator versions our services use, so every release comes with a list of values whose result changed.

About this answer

Last updated
12 November 2026
Versions it names
Spring Boot 2.6
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "You want to offer shared constraints such as @ValidCurrency, @ValidCountry and...": https://scrivio-interview-library.netlify.app/spring-boot/request-validation/32035ad114/