Reputation: 283
I'm using Spring Validator (JSR 303) with annotation and would like to resolve the attribute (idEnveloppe) value in an error message. Consider this simple scenario:
@NotEmpty(message = "GCE-COT-DTC-RJFLX03 La donnée &idEnveloppe du bloc entête du flux de cotisation DSN n'est pas renseignée")
@NotNull(message = "GCE-COT-DTC-RJFLX03 La donnée &idEnveloppe du bloc entête du flux de cotisation DSN n'est pas renseignée")
@Pattern(regexp = "[0-9]{14}", message = "GCE-COT-DTC-RJFLX04 La donnée '${idEnveloppe}' du bloc entête du flux de cotisation DSN n'est pas valide}")
private String idEnveloppe;
print error:
private BindingResult bindAndValidate(final DsnCotFluxDto item) {
DataBinder binder = new DataBinder(item);
binder.setValidator(validator);
binder.validate();
// LOG.error(binder.getErrors().getBindingResult().toString());
return binder.getBindingResult();
}
/**
* Etude du cas des erreurs
* @param results résultat des validations
* @param item
* @throws BusinessException
*/
private void buildValidationException(final BindingResult results, final DsnCotFluxDto item) throws BusinessException {
StringBuilder msg = new StringBuilder();
String code;
String message;
String rejectedValue;
for (ObjectError error : results.getAllErrors()) {
code = error.getDefaultMessage().substring(0, 19);
message = error.getDefaultMessage().substring(20);
// rejectedValue = error.getObjectName().getRejectedValue();
msg.append("\n\t \t---Error code : -- " + code + " ---Error message : --" + message + "\n");
LOG.warn("\n\t \t---Error code : -- " + code + " ---Error message : --" + message + "\n");
}
// throw new ValidationException(msg.toString());
}
Thank you
Upvotes: 1
Views: 2082
Reputation: 283
i get them with this
rejectedValue = ((FieldError) error).getRejectedValue().toString();
After i insert them in the message string like:
message = new StringBuilder(message).insert(10, rejectedValue).toString();
and it work fine
Thank you
Upvotes: 0
Reputation: 15204
Here is the quote from documentation:
As of Hibernate Validator 5 (Bean Validation 1.1) it is possible to use the Unified Expression Language (as defined by JSR 341) in constraint violation messages. [...] The validation engine makes the following objects available in the EL context:
- the currently validated value (property, bean, method parameter etc.) under the name validatedValue
So, try the following:
@Pattern(regexp = "[0-9]{14}", message = "GCE-COT-DTC-RJFLX04 La donnée '${validatedValue}' du bloc entête du flux de cotisation DSN n'est pas valide}")
Upvotes: 3