Reputation: 73
I've been trying to make a custom validator so i can just use the @NotEmpty annotation for specific classes (java.util.Calendar or CommandItem in this case). But i get an exception:
javax.validation.UnexpectedTypeException: No validator could be found for type: com.bla.DocumentCommandItem
Now, the only thing i can think of as to why it doesn't work is that the @NotEmpty annotation itself declares this:
@Constraint(validatedBy = { })
So there is no direct association to the Validator class. But then how does it validate Strings and Collections?
This is my Validator class:
public class DocumentNotEmptyExtender implements ConstraintValidator<NotEmpty,DocumentCommandItem> {
@Override
public void initialize( NotEmpty annotation ) {
}
@Override
public boolean isValid( DocumentCommandItem cmdItem, ConstraintValidatorContext context ) {
if ( !StringUtils.hasText( cmdItem.getId() ) && (cmdItem.getFilename() == null || cmdItem.getFilename().isEmpty()) ) {
return false;
} else {
return true;
}
}
}
Is this even possible?
(as a side note... I've also received this exception when i was making my own similar annotation, but that one mysteriously disappeared. )
Thanks!
Upvotes: 3
Views: 2832
Reputation: 18990
You have to register your validator in a constraint mapping file like this:
<constraint-mappings
xmlns="http://jboss.org/xml/ns/javax/validation/mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=
"http://jboss.org/xml/ns/javax/validation/mapping validation-mapping-1.0.xsd">
<constraint-definition annotation="org.hibernate.validator.constraints.NotEmpty">
<validated-by include-existing-validators="true">
<value>com.foo.NotEmptyValidatorForDocumentCommandItem</value>
</validated-by>
</constraint-definition>
</constraint-mappings>
This mapping file must be registered in META-INF/validation.xml
:
<validation-config xmlns="http://jboss.org/xml/ns/javax/validation/configuration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/configuration">
<constraint-mapping>/your-mapping.xml</constraint-mapping>
</validation-config>
You can learn more in the Hibernate Validator reference guide and the Bean Validation specification.
Upvotes: 4
Reputation: 73
The solution is listed above by @Gunnar
It caused a few unexepected things though...
NotEmpty is basically a wrapper for the @NotNull and @Size(min=1) constraints. So there is no actual @NotEmpty implementation.
Making my own @NotEmpty implementation for DocumentCommandItem caused 2 things:
So my final solution for this problem:
Make a @Size implementation for DocumentCommandItem And Make a @NotEmpty implementation for String
(and possibly i'll have to make another @NotEmpty for Collections)
Upvotes: 2