In Spring, the Validator
interface is used for custom validation logic on objects, typically before saving them to a database or processing user input.
🧩 Purpose
- Validate fields of a Java object (e.g., form input).
- Can implement complex rules not possible with simple annotations (
@NotNull
,@Size
). - Works with Spring MVC’s
@Valid
or programmatically.
Key Interface
public interface Validator {
boolean supports(Class<?> clazz); // Check if the validator can validate this class
void validate(Object target, Errors errors); // Perform validation
}
Example
public class UserValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return User.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
User user = (User) target;
if (user.getUsername().isEmpty()) {
errors.rejectValue("username", "username.empty", "Username is required");
}
if (user.getPassword().length() < 6) {
errors.rejectValue("password", "password.short", "Password must be at least 6 characters");
}
}
}
Controller Usage:
@PostMapping("/register")
public String register(@ModelAttribute User user, BindingResult result) {
new UserValidator().validate(user, result);
if (result.hasErrors()) {
return "registerForm";
}
userService.save(user);
return "success";
}
🧠 Key Points
supports()
ensures the validator only validates compatible classes.validate()
adds errors toErrors
object, which Spring MVC binds to the view.- Can be combined with annotation-based validation for flexibility.