Baeldung

Java, Spring and Web Development tutorials

 

Bind Custom Validation Message in Spring
2025-10-25 19:05 UTC by Sandip Roy

1. Introduction

Enterprise Java development depends heavily on Spring. It’s a powerful framework that simplifies the process of building strong, scalable apps. We can use Spring to build REST APIs, microservices, or full-stack web apps efficiently and cleanly.

However, as apps become larger, they require clear and understandable validation. Custom validation messages solve this problem. Developers can use them to give users useful feedback instead of confusing error messages.

In this tutorial, we’ll discuss Spring Boot’s validation message system, how to configure it effectively, streamline error handling, and make message management more intuitive.

2. Binding Custom Validation Messages

To guide users and guarantee data integrity, validation is crucial. Spring Boot uses the Java Bean Validation framework (JSR-380), enabling developers to annotate fields with constraints such as @NotBlank, @Email, and @Min.

However, for improved localization and maintainability, we can bind error messages to external properties rather than hard-coding them.

2.1. Add Validation Dependency

To use validation annotations in our Spring Boot application, we need to include the Spring Boot Starter Validation dependency. This starter wraps Hibernate Validator, which is the reference implementation of the Bean Validation API (JSR-380).

For Maven Configuration, we’ll add the following to our pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

Once added, Spring Boot will automatically add the necessary components to support validation across our application, including REST controllers, service layers, and form inputs.

2.2. Annotate DTO with Message Keys

After setting up the validation dependency, let’s add annotations to our Data Transfer Objects (DTOs) to impose rules on incoming data.

Depending on our configuration, these annotations are included in either the jakarta.validation.constraints or javax.validation.constraints package.

Let’s use constraint annotations and reference message keys:

public class UserDTO {
    @NotBlank(message = "{user.name.notblank}")
    private String name;
    @Email(message = "{user.email.invalid}")
    private String email;
    @Min(value = 18, message = "{user.age.min}")
    private int age;
    // Getters and setters
}

@NotBlank verifies that the name field is not empty or null. @Email verifies the email field’s format, and @Min verifies that the person is at least eighteen years old.

We’ll use message keys such as user.name.notblank to convey error messages rather than hard-coding them directly into the annotation (e.g., message = “Name must not be blank”).

In the next step, we’ll use these keys from a properties file (ValidationMessages.properties).

2.3. Create and Structure Validation Messages

Let’s now create validation messages. The core of Spring Boot’s custom validation messaging is the ValidationMessages.properties file. It allows for cleaner logic, simpler maintenance, and localization support by externalizing error messages from our code.

We’ll need to place the file in our project’s directory path:

our-project/
└── src/
└── main/
└── resources/
└── ValidationMessages.properties

Spring Boot automatically detects this file if named correctly and placed in the classpath.

Every entry in the file associates a human-readable message with a message key that we’ll use in our DTO annotations, as shown example below:

# ValidationMessages.properties
user.name.notblank=Name must not be blank.
user.email.invalid=Please provide a valid email address.
user.age.min=Age must be at least 18.

These keys correspond to the message attributes in DTO:

@NotBlank(message = "{user.name.notblank}")
@Email(message = "{user.email.invalid}")
@Min(value = 18, message = "{user.age.min}")

3. Optional Message Source Configuration

By default, Spring Boot loads validation messages from ValidationMessages.properties on the classpath.

For example, if we want to support multiple languages, change the encoding, or use a different filename, we can explicitly configure a MessageSource bean. The following steps are optional, but highly recommended:

  • Internationalization (I18n) – Supporting multiple locales
  • Custom file naming – Using messages.properties or other names
  • Advanced control – Configuring fallback behavior, encoding, etc.

3.1. What Is a Message Source?

This Spring interface retrieves messages using keys and locales in .properties files. It is the main component of Spring’s i18n and validation messaging system.

To configure a MessageSource, we’ll add the following bean to our Spring Boot application class or a configuration class:

@Bean
public MessageSource messageSource() {
    ResourceBundleMessageSource source = new ResourceBundleMessageSource();
    source.setBasename("ValidationMessages");     // Name of your properties file (without .properties)
    source.setDefaultEncoding("UTF-8");           // Ensures proper character encoding
    source.setUseCodeAsDefaultMessage(true);      // Optional: fallback to key if message not found
    return source;
}

Here are the key properties and purpose:

Property Purpose
setBasename(“…”) Specifies the base name of the message file (e.g., ValidationMessages)
setDefaultEncoding(“UTF-8”) Ensures proper rendering of special characters and non-English text
setUseCodeAsDefaultMessage() Falls back to the key if no message is found (useful for debugging)

3.2. Supporting Multiple Languages

To support international users, we’ll create locale-specific files:

src/main/resources/
├── ValidationMessages_en.properties
├── ValidationMessages_fr.properties
├── ValidationMessages_ar.properties

Spring automatically resolves the appropriate file based on the user’s locale, which can be configured using browser preferences, HTTP headers, and configuration.

For example, ValidationMessages_fr.properties for French Localization.

4. Validate in Controller

The next step is to initiate validation and gracefully handle errors in our controller after we have annotated our DTO with validation constraints and bound custom messages.

Using the @Valid annotation and BindingResult interface, Spring Boot makes this easy. Let’s discuss a REST controller method that accepts a UserDTO object and validates it:

@PostMapping("/register")
public ResponseEntity<?> registerUser(@Valid @RequestBody UserDTO userDTO, BindingResult result) {
    if (result.hasErrors()) {
        List<String> errors = result.getFieldErrors()
          .stream()
          .map(FieldError::getDefaultMessage)
          .collect(Collectors.toList());
        return ResponseEntity.badRequest().body(errors);
    }
    // Proceed with registration logic
    return ResponseEntity.ok("User registered successfully");
}

The following table elaborates on the role of each component of the above code:

Component Role
@Valid Triggers validation on the incoming UserDTO object
BindingResult Captures validation errors (if any)
FieldError Represents a single field-level error
getDefaultMessage() Retrieves the custom message from ValidationMessages.properties

4.1. Why Use Binding Result?

Spring will throw an error if we don’t use BindingResult. Though it works, this is not the best option for changing error formats, multiple error aggregation, or generating structured JSON responses.

We are in complete control of how validation errors are handled and displayed when we use BindingResult.

Let’s take an example of a JSON Error Response when a user provides inaccurate data. The controller may return:

[
"Name must not be blank.",
"Please provide a valid email address.",
"Age must be at least 18."
]

This is clean, readable, and directly tied to the custom messages.

5. Conclusion

In this article, we discussed how binding custom validation messages in Spring Boot simplifies user feedback. This is done by externalizing error messages into properties files.

Further, we elaborated on how a clean, maintainable, and user-friendly validation flow can be created in a few simple steps. This includes adding validation dependencies, annotating DTOs, configuring message sources, and handling errors in controllers. 

This method further facilitates localization and scalable application design in addition to increasing clarity. 

The tested code is available over on GitHub.

The post Bind Custom Validation Message in Spring first appeared on Baeldung.
       

 

Content mobilized by FeedBlitz RSS Services, the premium FeedBurner alternative.