AndroidTank AndroidTank - 1 year ago 219
Java Question

How to use custom error messages in Hibernate Validator without spring?

Is it possible to have custom error messages in separate file without using spring framework?
I'm developing API using hibernate 5+, jersey, jackson and

hibernate-validator 5.2.2.Final
for valdiation. I have found that i need to do declaration of file with custom error messages, but i don't where to do it.

How my code should look like by examples:

public class Account {

private int id;
@NotNull(message = "{}")
@Length(min = 1, max = 150, message = "{}")
private String name;
@NotNull(message = "{account.lastname.null}")
@Length(min = 1, max = 150, message = "{account.lastname.length}")
private String lastName;

with errorMessages.xml file with structure as: Name value is missing. Name has to be between {min} and {max}.

Tested approach

I have tried it with static final variables, but i can not use methods to return messages:

public class ValidationMessages {

public static String ACCOUNT_NAME_LENGTH(int min, int max)
return "Name has to be between "+min+" and "+max+".";
public static final String ACCOUNT_NAME_NULL = "Name value is missing.";

public class Account {

private int id;
@NotNull(message = ValidationMessages.ACCOUNT_NAME_NULL)
@Length(min = 1, max = 150 message =ValidationMessages.ACCOUNT_NAME_LENGTH(1,150))
private String name;
@NotNull(message = ValidationMessages.ACCOUNT_LASTNAME_NULL)
@Length(min = 1, max = 150 message = ValidationMessages.ACCOUNT_NAME_LENGTH(1,150))
private String lastName;

Answer Source

errorMessages.xml had to been renamed to .properties and i had to move it to /resources folder

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download