简体   繁体   中英

Use JAX-303 (bean-validation) annotations with custom type

I have a web application that is using Jersey2 to publish various REST services.

In this project, I am using the javax.validation annotations to validate the various inputs. However, I have some custom data types (Money, Percentage) where I would like to provide min and max validation in some cases.

However, if I annotate the field with @Min or @Max, I get an error message that there is no validator, which is the expected behavior, because my object is a complex data type.

I have successfully implemented a custom annotation with validator that provides this functionality, but I would prefer to reuse the existing annotation and supply my own validator for this data type, but I can't find any documentation on how to do this. Is it possible? If so, how do I register my custom validator for my data type?

It is possible to register your own validators for existing constraint annotations. You can do so by providing a list of such validators in META-INF/services/javax.validation.ConstraintValidator file. This would use the Service Loader mechanism to find your constraint validators and add them to the validation engine. For a more detailed explanation please check the next post - Adding custom constraint definitions via the Java service loader , and "Use standard constraints for non standard classes" section in particular.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM