Spring MVC Validation Interview Questions and Answers
Master Spring MVC Validation with interview questions covering Bean Validation, Jakarta Validation, @Valid, @Validated, validation annotations, custom validators, BindingResult, validation groups, and production best practices.
Introduction
Every enterprise application must validate incoming user data before processing it.
Examples
- User Registration
- Banking Fund Transfer
- Loan Applications
- Insurance Claims
- Product Orders
- Payment Processing
Without validation, applications become vulnerable to
- Invalid input
- SQL Injection
- Business rule violations
- Data corruption
- Security vulnerabilities
Spring MVC integrates with Jakarta Bean Validation (Hibernate Validator) to perform automatic request validation.
Validation happens before business logic executes, ensuring only valid data reaches the service layer.
Validation Architecture
flowchart LR
Client --> HTTPRequest
HTTPRequest --> DispatcherServlet
DispatcherServlet --> Validator
Validator --> ValidDTO
ValidDTO --> Controller
Validator --> ValidationErrors
ValidationErrors --> Client
Q1. What is Validation in Spring MVC?
Answer
Validation is the process of verifying whether incoming data satisfies predefined rules before processing.
Examples
- Required fields
- Email format
- Password length
- Numeric range
- Date validation
- Business constraints
Spring performs validation automatically when configured.
Q2. What is Bean Validation?
Bean Validation is the Java standard for object validation.
Spring Boot uses
- Jakarta Validation
- Hibernate Validator
Example
@NotNull
@Email
@Size
Validation rules are declared using annotations.
Q3. What is @Valid?
@Valid triggers validation for an object.
Example
@PostMapping
public ResponseEntity<?> save(
@Valid
@RequestBody CustomerRequest request){
}
Spring validates the object before entering the controller method.
Q4. What is @Validated?
@Validated is a Spring-specific annotation.
Advantages
- Supports validation groups
- Method validation
- Class-level validation
Example
@Validated
@Service
public class PaymentService {
}
Use @Validated when group-based validation is required.
Q5. What are common validation annotations?
| Annotation | Purpose |
|---|---|
@NotNull |
Value must not be null |
@NotBlank |
String cannot be blank |
@NotEmpty |
Collection/String cannot be empty |
@Size |
Length validation |
@Min |
Minimum value |
@Max |
Maximum value |
@Positive |
Positive numbers |
@Negative |
Negative numbers |
@Email |
Valid email format |
@Pattern |
Regular expression validation |
@Past |
Past date |
@Future |
Future date |
Example
@NotBlank
@Email
private String email;
Q6. What is BindingResult?
BindingResult stores validation errors.
Example
public ResponseEntity<?> save(
@Valid
@RequestBody CustomerRequest request,
BindingResult result){
}
Example
if(result.hasErrors()){
}
It prevents immediate validation exceptions.
Q7. What are Custom Validators?
Sometimes built-in annotations are insufficient.
Examples
- PAN Number
- Aadhaar
- Account Number
- Employee ID
- Credit Card Rules
Spring allows creating custom validation annotations.
Custom Validation Flow
flowchart LR
Request --> CustomValidator
CustomValidator --> Valid
CustomValidator --> Invalid
Q8. What are Validation Groups?
Validation Groups allow different validation rules for different operations.
Example
Create Customer
Password Required
Update Customer
Password Optional
Validation groups avoid duplicate DTOs.
Q9. What happens if validation fails?
Workflow
- Validation executes.
- Errors collected.
- Exception or BindingResult created.
- Error response returned.
Validation Failure
flowchart TD
Request --> Validator
Validator --> Success
Validator --> ValidationErrors
ValidationErrors --> HTTP400
REST APIs generally return 400 Bad Request.
Q10. Validation Best Practices
Validate DTOs
Avoid validating entities.
Use Bean Validation
Prefer annotations over manual validation.
Return Meaningful Errors
Include field names and messages.
Centralize Error Handling
Use @ControllerAdvice.
Validate Business Rules in Service Layer
Keep controller validation focused on input integrity.
Banking Example
flowchart TD
PaymentRequest --> BeanValidation
BeanValidation --> PaymentController
PaymentController --> PaymentService
BeanValidation --> ValidationError
ValidationError --> Client
Invalid requests never reach business logic.
Common Interview Questions
- What is Validation?
- What is Bean Validation?
- What is
@Valid? - What is
@Validated? - Difference between
@Validand@Validated? - Common validation annotations?
- What is
BindingResult? - What are Custom Validators?
- What are Validation Groups?
- Validation best practices?
Quick Revision
| Topic | Summary |
|---|---|
| Validation | Verify input correctness |
| Bean Validation | Standard validation framework |
@Valid |
Trigger object validation |
@Validated |
Spring validation with groups |
BindingResult |
Validation result holder |
| Custom Validator | Business-specific validation |
| Validation Group | Different rules per operation |
| DTO Validation | Recommended |
| HTTP 400 | Validation failure response |
| ControllerAdvice | Centralized error handling |
Complete Validation Lifecycle
sequenceDiagram
Client->>DispatcherServlet: HTTP Request
DispatcherServlet->>HttpMessageConverter: Convert JSON
HttpMessageConverter-->>DispatcherServlet: DTO
DispatcherServlet->>Validator: Validate DTO
Validator-->>DispatcherServlet: Validation Result
DispatcherServlet->>Controller: Invoke
Controller->>Service: Business Logic
Service-->>Controller: Response
Controller-->>Client: HTTP Response
Production Example – Banking Fund Transfer Validation
A banking application exposes
POST /api/v1/payments
Request DTO
public class PaymentRequest {
@NotBlank
private String fromAccount;
@NotBlank
private String toAccount;
@Positive
private BigDecimal amount;
}
Controller
@PostMapping("/payments")
public ResponseEntity<PaymentResponse> transfer(
@Valid
@RequestBody PaymentRequest request){
return ResponseEntity.ok(
paymentService.transfer(request));
}
Workflow
-
Mobile app sends payment request.
-
JSON is converted into
PaymentRequest. -
Bean Validation checks:
- Account numbers are present.
- Amount is positive.
-
Invalid requests immediately return 400 Bad Request.
-
Valid requests reach
PaymentService.
flowchart LR
MobileApp --> JSONRequest
JSONRequest --> HttpMessageConverter
HttpMessageConverter --> PaymentRequestDTO
PaymentRequestDTO --> BeanValidator
BeanValidator --> Success
BeanValidator --> ValidationErrors
Success --> PaymentController
PaymentController --> PaymentService
ValidationErrors --> HTTP400
@Valid vs @Validated
| Feature | @Valid |
@Validated |
|---|---|---|
| Standard | Jakarta Bean Validation | Spring Framework |
| Nested Validation | ✅ | ✅ |
| Validation Groups | ❌ | ✅ |
| Method Validation | ❌ | ✅ |
| Class-Level Validation | ❌ | ✅ |
| Most Common Usage | Controller Request DTOs | Services and advanced validation |
Frequently Used Validation Annotations
| Annotation | Example |
|---|---|
@NotNull |
Required object |
@NotBlank |
Required text |
@NotEmpty |
Non-empty collection/string |
@Size(min=3,max=20) |
Username length |
@Email |
Email format |
@Pattern |
Regex validation |
@Positive |
Amount |
@PositiveOrZero |
Balance |
@Past |
Date of Birth |
@Future |
Appointment Date |
Enterprise Validation Flow
flowchart TD
Client --> Controller
Controller --> BeanValidation
BeanValidation --> ServiceValidation
ServiceValidation --> Repository
Repository --> Database
Controller validation checks request structure and field correctness.
Service validation enforces business rules such as
- Sufficient balance
- Daily transfer limit
- Duplicate payment prevention
- Fraud detection
Key Takeaways
- Validation ensures that only valid input reaches business logic, improving application reliability and security.
- Spring Boot integrates Jakarta Bean Validation through Hibernate Validator, making validation annotation-driven and easy to maintain.
@Validis typically used for validating request DTOs in controllers, while@Validatedsupports validation groups and method-level validation.- BindingResult captures validation errors, allowing applications to return structured error responses instead of failing immediately.
- Custom validators are useful for domain-specific rules that cannot be expressed using standard annotations.
- Use DTOs rather than JPA entities for request validation to avoid exposing persistence models.
- Business rules should be validated in the service layer, while structural input validation belongs in the controller layer.
- Combining Bean Validation, global exception handling, and standardized error responses results in robust, enterprise-ready REST APIs.