Spring Boot Validator Doesn't Return Custom Error Message: A Comparison of Two Fields

Abstract: Resolve Spring Boot validators failing to return custom error messages by correctly handling BindingResult and configuring constraint annotations.

Created: 2026-10-02 by
Spring Boot validators fail to return custom error messages when the @Valid annotation is used without proper binding or when the validation logic in the controller does not correctly process the BindingResult object. This issue typically stems from missing imports, incorrect method signatures, or a misunderstanding of how JSR-380 constraints interact with Spring MVC's data binding mechanism. By ensuring that your controller methods accept a BindingResult parameter immediately after the validated object and by verifying that your entity classes are properly annotated, you can resolve these silent failures and ensure that user-friendly, custom error messages are returned in the API response.

Understanding the Validation Flow

To debug why custom messages are not appearing, it is essential to understand the lifecycle of request validation in Spring Boot. When a client sends a POST or PUT request to an endpoint protected by validation, Spring MVC uses a Validator implementation (usually LocalValidatorFactoryBean) to check the incoming data against the constraints defined on the model class. If violations occur, they are stored in a BindingResult object associated with the specific field or object being validated. The most common reason for missing custom messages is that the BindingResult is not being checked in the controller. If you annotate your controller method with @Valid but do not include a BindingResult argument immediately following the model parameter, Spring will throw a MethodArgumentNotValidException. While this exception contains the validation errors, if your global exception handler is not configured to extract the specific message from the constraint violation, the default system message may be returned instead of your custom one. Another frequent oversight involves the placement of the @Valid annotation. It must be placed on the parameter representing the DTO or Entity class. Additionally, ensure that you have imported javax.validation.Valid (or jakarta.validation.Valid in Spring Boot 3.x) rather than a different package that might not trigger the automatic validation process. Without this correct import, Spring treats the object as a regular bean and skips the validation phase entirely, meaning no error messages are generated at all. Can't Access Static Resources in Spring Boot Application

Configuring Custom Messages in Annotations

Custom error messages are defined directly within the constraint annotations on your model fields. For example, if you want to customize the message for a @NotBlank field, you modify the annotation as follows:
@NotBlank(message = "Username cannot be empty")
private String username;
If you are comparing two fields, such as checking if a password matches a confirmation password, you need a custom validator class. Create a class that implements ConstraintValidator<YourAnnotation, YourObject>. In the isValid method, perform your logic. To associate a message with this custom annotation, define it in the annotation itself:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = PasswordMatchValidator.class)
public @interface PasswordMatch {
    String message() default "Passwords do not match";
    Class[] groups() default {};
    Class[] payload() default {};
}
Ensure that the message attribute in the annotation definition matches the string you expect to see. If you rely on externalized messages in messages.properties, ensure that the key corresponds exactly to the message value or use the message attribute to reference the property file key using the ${...} syntax.

Handling Validation Errors in the Controller

Once validation runs, the controller must explicitly handle the results. The standard pattern is to check if the BindingResult has any errors before proceeding with business logic.
> register(@Valid @RequestBody UserRegistrationDto registration, BindingResult result) {
    Map errors = new HashMap<>();
    
    if (result.hasErrors()) {
        result.getFieldErrors().forEach(error -> 
            errors.put(error.getField(), error.getDefaultMessage())
        );
        return ResponseEntity.badRequest().body(errors);
    }
    
    // Proceed with registration
    return ResponseEntity.ok().build();
}
In this snippet, we iterate over FieldErrors to build a map of field names to their custom messages. If you are using a global exception handler, you might prefer to let the exception propagate and catch it in a @ControllerAdvice class. However, for immediate feedback, checking BindingResult directly gives you full control over the response structure. Ensure that error.getDefaultMessage() returns your custom text; if it returns null, check that the annotation was correctly processed and that no default fallback is overriding your setting. Troubleshooting OAuth2.0 Access Token Response

Debugging Common Pitfalls

Several subtle issues can prevent custom messages from displaying. First, verify that your project includes the necessary dependencies. For Spring Boot 2.x, you need spring-boot-starter-validation which brings in Hibernate Validator. For Spring Boot 3.x, this is included by default, but ensure you are using jakarta.validation packages. Second, check for conflicting validators. If you have multiple validators running on the same field, ensure they are not overriding each other’s messages. Third, inspect the HTTP response headers and body using tools like Postman or curl. Sometimes the message is present in the JSON response, but the frontend client fails to parse it correctly, leading developers to believe the backend is failing. Finally, ensure that your DTOs are immutable or have proper constructors. If Spring cannot instantiate the object to bind data, validation may fail silently or throw a different exception. Using Lombok’s @Data or @Builder can help, but ensure that the builder pattern is compatible with Jackson deserialization if you are using @RequestBody.

Frequently Asked Questions

Why is my custom message showing the default constraint message?

This usually happens because the message attribute in your annotation was not set correctly, or you are referencing a property key that does not exist in your messages.properties file. Check that the string literal in the message attribute matches your intended output, or verify that the property file is loaded in the classpath.

How do I validate two fields together, like password and confirm password?

You need to create a custom annotation at the class level, not the field level. Implement a ConstraintValidator that takes the entire object as input, allowing you to compare both fields. Apply this annotation to the DTO class and ensure the controller validates the object, triggering the custom validator logic.

Can I use internationalization (i18n) for validation messages?

Yes, Spring supports i18n for validation messages. You can define keys in a ValidationMessages.properties file and reference them in your annotations using the ${key} syntax. Ensure that the LocalValidatorFactoryBean is configured to use a MessageSource that resolves these properties based on the current locale.

What if I get a MethodArgumentNotValidException instead of my custom errors?

This exception indicates that validation failed, but the error was not handled gracefully in the controller. You should either add a BindingResult parameter to your controller method to handle errors manually, or implement a @ControllerAdvice with a @ExceptionHandler(MethodArgumentNotValidException.class) to convert the exception into a structured response containing your custom messages.

Does @Valid work on nested objects automatically?

Yes, if you have a nested object inside your DTO, you must place the @Valid annotation on the field of the nested object. This tells Spring to recursively validate the nested object. Without @Valid on the nested field, only the top-level fields will be validated, and any custom messages in the nested class will be ignored.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More