I' a little bit stuck in setting up my custom bean validation messages correctly. I've added the following constraint definition and put it onto some beans better say attributes.
@Constraint(validatedBy = NobleValidator.class)
@Documented
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
public @interface Noble {
String message() default "NOT_NOBLE";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Ok now I just implemented the custom validator "NobleValidator". All this goes straight forward. But here comes my issue. If I am trying to validate a bean by running the validation like this
// ...
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<Person>> s = validator.validate(p, new Class[]{});
if (s == null || s.isEmpty()) {
// Do some suff
} else {
for (ConstraintViolation<Person> cv : s) {
LOGGER.error(String.format("Constraint violation: %s", cv.getMessage()));
}
}
// ...
Okay the validation works but the result is not as expected. I get "Constraint violation: NOT_NOBLE". So I guess the validator was able to look up my property file and so it can't replace the key by the correct message text. The ValidatorMessages.properties simply looks like this:
NOT_NOBLE=Foo Bar is not noble
The spec (JSR303) says that I have to put the ValidationMessages.properties to my classpath root which I expect should be MyDeploymentUnit.war/WEB-INF/classes/ValidationMessages.properties and this is how my app was build and deployed. For debugging reasons I added this to my custom validator to make sure the file is there and set up correctly
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
InputStream is = getClass().getClassLoader().getResourceAsStream("ValidationMessages.properties");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String l = null;
try {
while ((l = br.readLine()) != null) {
LOGGER.info(String.format("Line: %s", l));
}
} catch (IOException ex) {
LOGGER.error(ex.getMessage());
}
// Validation logic goes here
The code above works perfectly fine. I'm getting all the lines specified in ValidationMessages.properties
Currently I am using JBossAS7.0.2 so my anybody give me some piece of advise how to fix it and receive the resolved text instead of the key? Thanks a lot
Wrap your message key in curly brackets:
@Constraint(validatedBy = NobleValidator.class)
@Documented
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
public @interface Noble {
String message() default "{NOT_NOBLE}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}