Custom Error Messages

Learn how to override Spring MVC's default validation messages with our custom error messages.

We can specify error messages inside the annotation like this:

@NotNull(message="This is a required field.")
@Past(message="Date must be in the past.")
@Min(value=1, message="Value must be greater than or equal to 1.")

These error messages override the default error messages for the constraints provided by the Hibernate validator. The default messages are located in the ValidationMessages.properties file inside the hibernate-validator jar file.

Type mismatch errors

This type of error occurs in non-String fields when data cannot be converted into the desired datatype. For example, if a String in entered in an int field.

In such a case, Spring shows a default message, which shows why the exception was thrown. Custom messages can be created in messages.properties file.

Another approach is to externalize the error messages by placing them in a properties file. This file is called messages.properties and must be placed in the resources folder. When there is a constraint violation, Spring will check the messages.properties file and look for a key matching the error code. If the key is found it will display the custom error message, else use the default error message for the constraint violation.

messages.properties file

We will first create a new folder called resources under the WEB-INF directory. The location of the properties file is important. Next, we will create the properties file in the resources folder. The name of the file is equally important. It should be called messages.properties. This file contains a key value pair of the error type and the corresponding error message.

Finding the error code

To find the error code, we can use the BindingResult object, which contains the result of validation.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.