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?
The @Valid annotation will tell spring to go and validate the data passed into the controller by checking to see that the integer numberBetweenOneAndTen is between 1 and 10 inclusive because of those min and max annotations.
The @Validated annotation is a class-level annotation that we can use to tell Spring to validate parameters that are passed into a method of the annotated class. We'll learn more about how to use it in the section about validating path variables and request parameters.
The @Valid annotation ensures the validation of the whole object. Importantly, it performs the validation of the whole object graph. However, this creates issues for scenarios needing only partial validation. On the other hand, we can use @Validated for group validation, including the above partial validation.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With