Quick revision
The short answer
We create an annotation with @Target(ElementType.TYPE) and a ConstraintValidator for the DTO type. Its isValid returns true if either date is null, leaving required-ness to @NotNull, and otherwise checks that startDate is before endDate. To report the error on the endDate field instead of on the whole object, we call context.disableDefaultConstraintViolation() and then context.buildConstraintViolationWithTemplate(message).addPropertyNode("endDate").addConstraintViolation().
What to remember
In this answer, we wrote a class-level constraint: an annotation with @Target(TYPE) and a validator for the DTO that returns true when either date is null and compares the dates otherwise. To report the error where the user can fix it, we disabled the default violation with context.disableDefaultConstraintViolation() and built a new one with buildConstraintViolationWithTemplate(message).addPropertyNode("endDate").addConstraintViolation(), then tested that the path is endDate.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We create an annotation with @Target(ElementType.TYPE) and a ConstraintValidator for the DTO type. Its isValid returns true if either date is null, leaving required-ness to @NotNull, and otherwise checks that startDate is before endDate. To report the error on the endDate field instead of on the whole object, we call context.disableDefaultConstraintViolation() and then context.buildConstraintViolationWithTemplate(message).addPropertyNode("endDate").addConstraintViolation().
Background to this question
Field annotations check one value at a time, but many rules compare two fields: a booking ends after it starts, a price range has min below max, a password matches its confirmation. Bean Validation handles these with class-level constraints, which see the whole object. The detail that makes them pleasant for clients is where the error is reported: on the field the user has to fix, not on the object as a whole. In this answer, we will see why a field constraint cannot do this, write the annotation and the validator, move the violation to endDate, and test the result.
1Why a Field Constraint Is Not Enough
A field-level validator receives only the value of its field. A validator on endDate sees a LocalDate and nothing else, so it cannot know the start date. The rule belongs to the object, so the constraint has to be placed on the class. Its validator then receives the whole DTO and can compare any fields it likes.
By default, a violation from a class-level constraint has an empty property path, meaning it is attached to the object itself. In a Spring MVC response that becomes a global error rather than a field error, and a form cannot show it next to an input. That is the second half of the question, and we will fix it with the ConstraintValidatorContext, the object the provider passes to isValid for building custom violations.
2Writing the Annotation and the Validator
The annotation targets TYPE, so it can only go on classes and records. The validator is typed to the DTO it checks.
Returning true for missing dates follows the usual convention: each constraint checks one thing, and @NotNull on the fields already reports a missing date. If we returned false here as well, the client would get two errors for the same problem.
3Moving the Violation to endDate
Now let us look closely at the three calls at the end, because their order matters. When isValid returns false, the provider normally creates one violation from the annotation's message with the path of the object. disableDefaultConstraintViolation() switches that off; without it, we would get two violations, one for the object and one for endDate.
buildConstraintViolationWithTemplate(...) starts a new violation with a message template, here the annotation's own message, so it can still be overridden where the annotation is used. addPropertyNode("endDate") sets the path to the endDate property of the validated object. And addConstraintViolation() finally adds it to the result. If we forgot that last call, nothing would be reported, and only the default would have been disabled, so the validation would fail with no violation explaining why.
- Is either date null?YesReturn true, @NotNull handles itNoCompare the dates
- Is startDate before endDate?YesReturn trueNoBuild a custom violation
- disableDefaultConstraintViolation()no object-level error
- buildConstraintViolationWithTemplate(...)same message template
- addPropertyNode("endDate").addConstraintViolation()path
endDate - Return false
6 steps in order. Play them, or step through them one at a time.
4Seeing It in a Request and a Test
With @Valid on the controller parameter, the class-level constraint runs together with the field constraints, and Spring reports the violation as a field error on endDate.
Notice the rule we chose: start strictly before end. If a booking may start and end on the same day, the check becomes !r.endDate().isBefore(r.startDate()). That is a business decision worth stating in the message, for example end date must be on or after the start date.
5Reusing the Constraint for Other DTOs
Typing the validator to BookingRequest ties it to one class. If several DTOs have date ranges, we can define a small interface, such as HasDateRange with startDate() and endDate() methods, let each record implement it, and type the validator as ConstraintValidator<ValidDateRange, HasDateRange>. The provider picks the validator by the type of the annotated object, so one annotation serves every DTO that implements the interface. Attribute names on the annotation, such as start() and end(), with reflection are another option, but they lose compile-time safety, so the interface is usually the better design.
6Follow-up questions
Why not just check the dates in the service?
We can, and for rules that need data from the database we must. But a date range on a single request is a pure input rule, and checking it with the other constraints means the client gets all field errors in one 400 response, including this one, before any transaction starts.
What does addPropertyNode do for nested objects?
It adds a node relative to the object being validated. If BookingRequest were nested inside an OrderRequest under the field booking, the resulting path would be booking.endDate, so clients still see exactly which input is wrong.
Does the order of class-level and field constraints matter?
The specification does not guarantee an order, and all violations are collected, so the client gets both field and class-level errors together. If we want the class-level check to run only when the fields are valid, we can use a group sequence, but returning true for null values usually makes that unnecessary.
7Conclusion
In this answer, we wrote a class-level constraint: an annotation with @Target(TYPE) and a validator for the DTO that returns true when either date is null and compares the dates otherwise. To report the error where the user can fix it, we disabled the default violation with context.disableDefaultConstraintViolation() and built a new one with buildConstraintViolationWithTemplate(message).addPropertyNode("endDate").addConstraintViolation(), then tested that the path is endDate.
Open with
A field constraint only sees its own value, so a rule that compares two fields has to be a class-level constraint. I would create an annotation, say @ValidDateRange, with @Target(ElementType.TYPE), runtime retention, @Constraint pointing to the validator, and the usual message, groups and payload attributes, and put it on the BookingRequest record.
Then, if they want more
The validator implements ConstraintValidator<ValidDateRange, BookingRequest>. In isValid, if either date is null I return true, because @NotNull on the fields already reports missing values and I do not want two errors for one problem. Otherwise I check startDate.isBefore(endDate).
If that fails, the default violation would be attached to the whole object, which becomes a global error that a form cannot show next to a field. So I call context.disableDefaultConstraintViolation(), then context.buildConstraintViolationWithTemplate with the message, addPropertyNode("endDate"), and addConstraintViolation, and return false. Without disabling the default I would get two violations, and without the final addConstraintViolation I would get none.
Then I test through a real validator that there is exactly one violation with the path endDate. If several DTOs need it, I would type the validator to a small HasDateRange interface.
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.
- Official documentation
- Spring Framework reference, Spring Web MVC
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 class-level constraint that checks startDate is before endDate and reports the...": https://scrivio-interview-library.netlify.app/spring-boot/request-validation/4c434203ad/