8

I have a POJO named sport with properties sportID, sportName, number of players. Using annotated validation I wrote my own annotation constraint to check if sportName exists in the database already or not. It works great when trying to add a sportName, however if I try to update players without changing the sportName the validation fails as well.

Is there any way to pass in a parameter in annotated validation? For example I would like to pass in sportID to the sportName contraint check so that I can exclude that ID in the db query.

Or is there a better way of doing this? In my controller should I let Spring validate inputs (with @Valid) and then if there are no errors call a validate function to check for business rules?

Felix
  • 610
  • 2
  • 9
  • 21

1 Answers1

5

A better way would be using Validation Groups. (Spring MVC and JSR-303 Validation Groups)

Then you can have the default validation group without the "not exits validator". And have an extra group with the "not exits validator". This would allow you to trigger the "not exits validator" only when you need it. (Unfortunately it is not direct supported in Spring 3.0, there you have to start the validation "by hand")

An other way would be not to implement the validator like a field validator, but more like a class validator. -- Have a look at the different solutions discussed for cross field validation in this Stack Overflow Question. It will give you an idea how to access the id field.

Community
  • 1
  • 1
Ralph
  • 118,862
  • 56
  • 287
  • 383
  • Used that link you sent me and it worked. I actually read that yesterday but couldn't figure out how to pass an int through but realized as I was implementing it that it's looking for a String of the name of the field and the BeanUtils.getProperty code is what actually gets the value, which I can then cast as an Integer. – Felix Feb 29 '12 at 20:01
  • It's extremely interesting this comments in the same blog: https://digitaljoel.nerd-herders.com/2010/12/28/spring-mvc-and-jsr-303-validation-groups/#comment-239 – Paco Abato Sep 01 '18 at 17:24