Scrivio Interview library
CodingFoundations5 min read · updated 12 November 2026

Write a custom constraint @ValidIsoCurrency for a String field.

We declare an annotation @ValidIsoCurrency marked with @Constraint(validatedBy = IsoCurrencyValidator.class), with the three required attributes message, groups and payload. The validator implements ConstraintValidator<ValidIsoCurrency, String> and its isValid returns true for null, so that @NotNull alone decides whether the field is required, and otherwise checks the code against the ISO 4217 currencies known to java.util.Currency, either with Currency.getInstance in a try block or with a precomputed set of allowed codes.

Background to this question

Built-in constraints cover shapes such as length and pattern, but many fields need a domain check: a currency code, a country code, a product SKU format. A @Pattern(regexp = "[A-Z]{3}") would accept XYZ, which is not a currency. A custom constraint gives the rule a name, keeps it in one place, and behaves exactly like the standard annotations. Writing one is a common coding exercise because it shows we understand how Bean Validation is put together. In this answer, we will recap the two parts of a constraint, write the annotation, write the validator, use and test it, and look at a stricter variant with an allowed list.

1A Quick Recap of a Custom Constraint

A Bean Validation constraint has two parts. The annotation is what we put on fields; it carries the message and configuration, and @Constraint on it names the class that does the checking. The validator is a class implementing ConstraintValidator<A, T>, where A is the annotation type and T is the type of value it checks. When the provider, Hibernate Validator, finds the annotation on a field, it creates the validator, calls initialize once with the annotation, and then calls isValid for each value.

The specification requires every constraint annotation to declare three attributes: message, the default error message or a message key; groups, for validation groups; and payload, a rarely used way to attach metadata such as a severity. If one is missing, the provider rejects the annotation when it first meets it.

Step throughHow the provider runs a custom constraint
ValidatorIsoCurrencyValidatorjava.util.Currency
initialize(annotation), once
isValid("EUR", context)
getInstance("EUR")
Currency EUR
true
isValid("XYZ", context)
getInstance("XYZ")
IllegalArgumentException
false: violation reported

9 messages in order. Play them, or step through them one at a time.

2Writing the Annotation

The annotation declares where it can be used, that it is kept at runtime, and which validator implements it.

Java
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.*;
@Documented
@Constraint(validatedBy = IsoCurrencyValidator.class)
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidIsoCurrency {
String message() default "{validation.currency.iso}"; // key in ValidationMessages.properties
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
# ValidationMessages.properties
validation.currency.iso=must be an ISO 4217 currency code such as EUR or USD

RetentionPolicy.RUNTIME is essential: without it, the annotation is dropped at compile time and the validator never runs, with no error. TYPE_USE in the targets lets us write List<@ValidIsoCurrency String>. The message in braces is a key, which keeps text out of code and allows translations.

3Writing the Validator

The validator checks one String. It treats null as valid and asks the JDK whether the code is a known currency.

Java
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import java.util.Currency;
public class IsoCurrencyValidator implements ConstraintValidator<ValidIsoCurrency, String> {
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value == null) {
return true; // required-ness is @NotNull's job
}
try {
Currency.getInstance(value); // throws for unknown or malformed codes
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
}
// isValid("EUR") -> true
// isValid("eur") -> false (codes are upper case)
// isValid("XYZ") -> false
// isValid(null) -> true

Returning true for null follows the convention of every built-in constraint, and the reason is composition. If @ValidIsoCurrency rejected null, an optional currency field would be impossible to express. With the convention, @ValidIsoCurrency means if present, it must be a real code, and @NotNull @ValidIsoCurrency means required and real. Notice also that we do not trim or upper-case the value; validation should check what was sent, and normalising belongs in the binding or mapping step if we want it.

4Using and Testing the Constraint

The annotation now works like any standard one, on DTO fields, parameters and type arguments.

Java
public record PaymentRequest(
@NotNull @Positive BigDecimal amount,
@NotNull @ValidIsoCurrency String currency,
List<@ValidIsoCurrency String> acceptedCurrencies) {}
class IsoCurrencyValidatorTest {
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
@Test void rejectsUnknownCode() {
var v = validator.validate(new PaymentRequest(BigDecimal.TEN, "XYZ", List.of()));
assertThat(v).extracting(c -> c.getPropertyPath().toString()).containsExactly("currency");
}
@Test void acceptsEuro() {
assertThat(validator.validate(new PaymentRequest(BigDecimal.TEN, "EUR", List.of()))).isEmpty();
}
}

Testing with a real Validator, rather than calling isValid directly, also proves that the annotation is wired correctly: retention, targets and the validatedBy class. A test that calls the validator method alone would pass even if the annotation were never picked up.

5A Stricter Variant With an Allowed Set

Currency.getInstance accepts every code the JDK knows, including funds and historical codes that our payment provider may not support. If the business supports only some currencies, a set of allowed codes is clearer and faster, because it avoids creating an exception for every invalid value.

Java
public class IsoCurrencyValidator implements ConstraintValidator<ValidIsoCurrency, String> {
private static final Set<String> CODES = Currency.getAvailableCurrencies().stream()
.map(Currency::getCurrencyCode)
.collect(Collectors.toUnmodifiableSet()); // or Set.of("EUR", "USD", "GBP") for supported ones
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
return value == null || CODES.contains(value);
}
}

Notice that this kind of business list can change, so if the supported currencies change often, the list belongs in configuration or in the payment service, and the annotation should check only that the code is a real ISO 4217 code.

6Follow-up questions

Can a ConstraintValidator be a Spring bean with injected dependencies?

Yes. In Spring, the validator factory creates ConstraintValidator instances through Spring's bean factory, so constructor injection works. For a currency check no dependency is needed, which keeps it fast and easy to use in plain unit tests.

Is the validator instance shared between threads?

Hibernate Validator typically creates one instance per constraint declaration and reuses it, so isValid may be called concurrently. That is why the validator should be stateless, or keep only immutable state such as the set of codes built once.

Could we just use @Pattern(regexp = "[A-Z]{3}")?

It checks the format but accepts any three letters, such as XYZ or AAA. It is fine as a cheap first filter, but only a check against the ISO 4217 list tells us the code is real, and a named annotation also documents intent better than a regular expression.

7Conclusion

In this answer, we wrote a custom constraint in two parts: the @ValidIsoCurrency annotation with @Constraint(validatedBy = IsoCurrencyValidator.class), runtime retention and the required message, groups and payload attributes, and a ConstraintValidator<ValidIsoCurrency, String> whose isValid returns true for null and checks the code with Currency.getInstance or a set of allowed codes. We tested it through a real Validator and saw when a stricter allowed list is the better choice.

What to say in the interviewAbout 70 seconds aloud

Open with

A custom constraint has two parts. First the annotation, @ValidIsoCurrency, which I mark with @Constraint(validatedBy = IsoCurrencyValidator.class), @Retention(RUNTIME), because otherwise it disappears at compile time and nothing is validated, and targets like FIELD, PARAMETER and TYPE_USE so it also works on list elements.

Then, if they want more

The specification requires three attributes: message, which I point to a key in ValidationMessages.properties, groups and payload, both defaulting to empty arrays. Second, the validator class, implementing ConstraintValidator<ValidIsoCurrency, String>. In isValid, I return true for null, following the convention of the built-in constraints, so that @NotNull alone decides whether the field is required and the currency can be optional elsewhere.

For a non-null value I call Currency.getInstance in a try block and return false on IllegalArgumentException, or, better for performance, I build a set of codes once from Currency.getAvailableCurrencies and check membership. If the business supports only some currencies, that set can be explicit. The validator should be stateless because the instance is reused across threads.

Then I test it through a real Validator, not by calling isValid directly, so the test also proves the annotation is wired correctly.

About this answer

Last updated
12 November 2026
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 "Write a custom constraint @ValidIsoCurrency for a String field.": https://scrivio-interview-library.netlify.app/spring-boot/request-validation/30edd4d17d/