Reputation: 817
I am required to use bean validation using XML.
We can validate the whole class by putting annotations just before the class declaration.
@AtLeastOneNotNull
public class SampleBean {
// ...
}
And then use reflection to loop over the fields.
How can I achieve the same thing using XML bean validation?
<constraint-mappings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/mapping validation-mapping-1.0.xsd" xmlns="http://jboss.org/xml/ns/javax/validation/mapping">
<default-package>my.package</default-package>
<bean class="SampleBean">
<!-- ? -->
</bean>
</constraint-mappings>
All I can declare after <bean>
is <field>
.
My goal is to validate multiple fields dependencies using XML bean validation.
For example :
field1
is null
then field2
isn'tUpvotes: 0
Views: 1343
Reputation: 2533
Please check the documentation for Bean Validation 2.0 (If you still use the older version - here's the same link to 1.0 version) There's Example 9.2 showing what you need:
<?xml version="1.0" encoding="UTF-8"?>
<constraint-mappings
xmlns="http://xmlns.jcp.org/xml/ns/validation/mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/validation/mapping
http://xmlns.jcp.org/xml/ns/validation/mapping/validation-mapping-2.0.xsd"
version="2.0">
<default-package>com.acme.app.domain</default-package>
<bean class="Customer" ignore-annotations="false">
<class ignore-annotations="true">
[...]
</class>
</bean>
</constraint-mappings>
So to answer your question you should be able to put:
<bean class="SampleBean" ignore-annotations="false">
<class ignore-annotations="true">
[...]
</class>
</bean>
and define your constraints. Also if you are using Hibernate Validator you might want to look at ScripAssert constraint - it would allow you to write a simple script check and you wouldn't need to write your own constraint for checking if at least one filed is not null. Hope this helps.
Upvotes: 1