Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Implement a Spring org.springframework.validation.Validator for a PasswordChangeForm that checks the new password differs from the old one and both confirmation fields match, and register it for one controller.

We write a PasswordChangeValidator that implements org.springframework.validation.Validator: supports returns true for PasswordChangeForm, and validate reports problems with errors.rejectValue("newPassword", "same.as.old", ...) for field errors or errors.reject(...) for object-level errors. We register it in the controller with @InitBinder("passwordChangeForm") and binder.addValidators(...), and mark the parameter with @Valid. addValidators keeps Bean Validation running alongside, and the errors appear in the BindingResult, or as MethodArgumentNotValidException for a request body.

Why this question is asked

Some rules are about the relation between fields rather than one field. The new password must differ from the old one, and the confirmation must match the new password. A field annotation cannot see the other fields, and writing a class-level Bean Validation constraint for a rule used in one form is a lot of ceremony. Spring's own Validator interface is a lightweight fit for exactly this, and interviewers ask it to see whether we know how it plugs into data binding and how it coexists with Bean Validation. In this answer, we will recap the interface, write the validator, see how error codes become messages, register it for one controller, and then test it without Spring MVC.

1A Quick Recap of Spring's Validator Interface

org.springframework.validation.Validator has two methods. supports(Class) tells Spring which types the validator can check. validate(Object target, Errors errors) does the checking and records problems in an Errors object, Spring's container for field errors and object-level errors, instead of throwing.

Spring MVC uses this interface during data binding. When it builds a form or body object for a controller method, it creates a WebDataBinder, a helper that copies request values onto the object and then runs the validators registered with it. Bean Validation also runs through this same mechanism, as we will see.

2Writing the Validator

Here is the form and the validator. The form keeps plain getters and setters so that Spring's binding and rejectValue can read the properties.

Java
public class PasswordChangeForm {
@NotBlank private String oldPassword;
@NotBlank @Size(min = 12) private String newPassword;
@NotBlank private String confirmPassword;
// getters and setters
}
public class PasswordChangeValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return PasswordChangeForm.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
PasswordChangeForm form = (PasswordChangeForm) target;
String newPw = form.getNewPassword();
if (newPw == null || errors.hasFieldErrors("newPassword")) {
return; // let @NotBlank and @Size report first
}
if (newPw.equals(form.getOldPassword())) {
errors.rejectValue("newPassword", "same.as.old", "must differ from the old password");
}
if (!newPw.equals(form.getConfirmPassword())) {
errors.rejectValue("confirmPassword", "mismatch", "must match the new password");
}
}
}

Notice the early return. If the new password is missing or already failed its own rules, comparing it with the others would only add confusing extra messages. rejectValue attaches an error to one field, so a form can show the message next to that input. When a rule concerns the object as a whole, we use errors.reject("passwords.invalid", "...") instead, which creates an object-level error.

3How the Error Codes Become Messages

The second argument of rejectValue, same.as.old, is an error code. The third is a default message used only if no translation is found. Spring's DefaultMessageCodesResolver expands the code into a list from most to least specific, and the MessageSource, Spring's lookup for translated messages, uses the first one it finds in messages.properties.

Java
// errors.rejectValue("newPassword", "same.as.old", ...) on object "passwordChangeForm" tries:
// same.as.old.passwordChangeForm.newPassword
// same.as.old.newPassword
// same.as.old.java.lang.String
// same.as.old
# messages.properties
same.as.old=The new password must be different from your current password.
mismatch.confirmPassword=The two new passwords do not match.

So one generic message can cover every use of a code, and a specific form can override it when it needs different wording. Bean Validation errors go through the same resolver, with the annotation name as the code, for example Size.passwordChangeForm.newPassword.

4Registering It for One Controller

A method annotated with @InitBinder in a controller runs each time that controller creates a WebDataBinder. Giving it the name passwordChangeForm limits it to the binder for that one model attribute or request body, whose default name is the class name with a lowercase first letter.

Java
@Controller
@RequestMapping("/account/password")
class PasswordController {
@InitBinder("passwordChangeForm")
void initBinder(WebDataBinder binder) {
binder.addValidators(new PasswordChangeValidator());
}
@PostMapping
String change(@Valid @ModelAttribute PasswordChangeForm passwordChangeForm, BindingResult result) {
if (result.hasErrors()) {
return "account/password"; // the page shows each field's message
}
accountService.changePassword(passwordChangeForm);
return "redirect:/account";
}
}
Step throughWhat happens when the form is posted
  1. WebDataBinder createdname: passwordChangeForm
  2. @InitBinder runsadds PasswordChangeValidator
  3. Request values boundoldPassword, newPassword, confirmPassword
  4. @Valid triggers validationBean Validation, then our validator
  5. Any errors?
    YesBindingResult has them, or MethodArgumentNotValidExceptionNocontroller method runs normally

5 steps in order. Play them, or step through them one at a time.

Three details matter here. First, @Valid is what triggers validation; without it no validator runs. Second, addValidators adds our validator next to the default one, so @NotBlank and @Size still run. setValidator would replace the default and silently turn Bean Validation off for this binder. Third, the name in @InitBinder matters: without it, the validator would be added to every binder in the controller, and Spring refuses a validator that does not support the binder's target type with an IllegalStateException.

For a REST endpoint with @Valid @RequestBody PasswordChangeForm, the same validator runs, but there is no BindingResult parameter, so Spring throws MethodArgumentNotValidException, which becomes a 400 and can be formatted by our error advice.

5Follow-up questions

How would you unit test this validator without Spring MVC?

We create the form, create an Errors object with new BeanPropertyBindingResult(form, "passwordChangeForm"), call validator.validate(form, errors) and assert on the result, for example that errors.getFieldError("newPassword").getCode() equals same.as.old. Since Spring Framework 6.1 there is also validator.validateObject(form), which returns an Errors object directly. No application context, no MockMvc, just a fast plain unit test per rule.

Why not register the validator globally?

A global validator set through WebMvcConfigurer.getValidator() replaces the default for every binder, which would remove Bean Validation unless we combine them ourselves. A rule for one form belongs with that form's controller, so @InitBinder with a name keeps it local and leaves everything else untouched.

Could this be a class-level Bean Validation constraint instead?

Yes, an annotation like @PasswordsDiffer on the class with a ConstraintValidator would work and is portable beyond Spring. It is worth it when several forms share the rule. For one form, the Spring Validator is shorter, and it can easily use other Spring beans through its constructor.

6Conclusion

In this answer, we wrote a Spring Validator for a password change form. supports limits it to PasswordChangeForm, and validate compares the fields and records problems with rejectValue for field errors or reject for object errors, whose codes are resolved against the MessageSource. We registered it for one controller with a named @InitBinder and addValidators, which keeps Bean Validation running, triggered it with @Valid, and saw where the errors appear for forms and for request bodies.

What to say in the interviewAbout 80 seconds aloud

Open with

I'd implement org.springframework.validation.Validator. supports returns PasswordChangeForm.class.isAssignableFrom of the class. In validate I cast the target, and if the new password is missing or already has a field error I return, so the Bean Validation messages come first.

Then, if they want more

Then if the new password equals the old one, I call errors.rejectValue on newPassword with the code same.as.old and a default message, and if the confirmation doesn't match, I reject confirmPassword with a mismatch code. For a rule about the whole object I'd use errors.reject instead.

The codes are resolved through the MessageSource, from the most specific form like same.as.old.passwordChangeForm.newPassword down to the plain code.

To register it for one controller, I add an @InitBinder method with the name passwordChangeForm and call binder.addValidators with my validator. addValidators matters: it keeps the default Bean Validation validator, whereas setValidator would replace it and turn off the @NotBlank and @Size checks. The controller parameter needs @Valid.

For a form I take a BindingResult and redisplay the page on errors; for a request body, Spring throws MethodArgumentNotValidException, which my advice turns into a 400. To unit test it I just call validate with a BeanPropertyBindingResult and check the codes.

About this answer

Last updated
12 November 2026
Versions it names
Spring Framework 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 "Implement a Spring org.springframework.validation.Validator for a PasswordChangeForm...": https://scrivio-interview-library.netlify.app/spring-boot/request-validation/ea815618f5/