AndroidTank AndroidTank - 13 days ago 5
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 = "{account.name.null}")
@Length(min = 1, max = 150, message = "{account.name.length}")
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:

account.name.null= Name value is missing.
account.name.length= 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 {

//ACCOUNT
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

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

Comments