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.")
Error messages in validation annotations

These error messages override the default error messages for the constraints provided by the Hibernate validator. The Hibernate Validator is the reference implementation of the Bean Validation API. The default messages for the annotations are located in the ValidationMessages.properties file inside the hibernate-validator jar file.

Press + to interact
Hibernate validator error messages
Hibernate validator error messages

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. We can create a custom message in messages.properties file. The properties file is placed in the WEB-INF/resources folder and is used to externalize the error messages. When there is a constraint ...

Access this course and 1400+ top-rated courses and projects.