Reputation: 355
I am trying to write a custom validator in a Spring MVC application. I would like to know if there a way to pass the @Model object to a custom spring validator?
Say, I have a Person object and Account object. I have to write a custom validator to validate Person, but the validation is dependent of the Account object and other objects in session.
For example, Person cannot have more than 3 accounts, account types have to be of specific category and not old than 3 years (this value, ie the number years is dynamic based on the profile logged in and is in session).
How can I pass both objects, especially @Model to the validator.
public class ServiceValidator implements Validator {
@Autowired
private ServiceDAO servicesDao;
@Override
public boolean supports(Class<?> clasz) {
return clasz.isAssignableFrom(Person.class);
}
@Override
public void validate(Object obj, Errors errors) {
Person subscriber = (Person) obj;
// How can I access @Model object here ???
}
Upvotes: 0
Views: 865
Reputation: 49915
Doubt if you can but have two workarounds:
a. If it is persisted data that you are looking for, probably it is just better to retrieve it once more in the validator and validate using that data, so for eg, in your case if you are validating person and persons account details are retrievable from DB, then get it from DB and validate in your validator using the retrieved data.
b. Probably this is a better approach if the number of places where you need to use the validator is fairly confined:
public class ServiceValidator {
@Autowired
private ServiceDAO servicesDao;
public void validate(Person subscriber, List<Account> accounts, ..., Errors errors) {
}
Just call the above validator directly from your requestmapped methods..
In your controller..
List<Account> accounts = //retrieve from session
serviceValidator.validate(subscriber, accounts, ...errors);
if (errors.hasErrors())..
else..
Upvotes: 1