So it is possible I will have different path variables I will need to validate for UUID and each will have a different name lets say. So how can I write the custom validator and have the message specific to the requestparam
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Great question! You want a custom UUID validator that can be applied to multiple path variables (or request params) with customized error messages per usage (e.g., different variable names).
How to achieve this:
Create a custom annotation with a message attribute (standard).
Use the annotation on each path variable with a custom message.
In the validator, just validate the UUID format.
Spring’s validation framework will inject the message you specify on the annotation.
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
public class UUIDValidator implements ConstraintValidator<UUID, String> {
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value == null || value.isEmpty()) {
return false; // or true if you want to allow null/empty
}
try {
java.util.UUID.fromString(value);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
}
3. Use in Controller with Custom Messages
java
import org.springframework.validation.annotation.Validated;
import jakarta.validation.constraints.NotBlank;
@RestController
@Validated // Important to enable validation on method parameters
public class MyController {
@GetMapping("/users/{userId}/orders/{orderId}")
public ResponseEntity<String> getUserOrder(
@PathVariable
@UUID(message = "User ID must be a valid UUID")
String userId,
@PathVariable
@UUID(message = "Order ID must be a valid UUID")
String orderId
) {
// If validation passes, proceed here
return ResponseEntity.ok("User ID and Order ID are valid UUIDs");
}
}
4. What happens on validation failure?
If either userId or orderId is invalid, Spring will throw a MethodArgumentNotValidException or ConstraintViolationException (depending on setup), and the message you specified in the annotation will be included in the validation error.
5. Optional: Customize the error response globally
You can create a global exception handler to catch validation errors and return a nice JSON response:
java
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity<Map<String, String>> handleConstraintViolation(ConstraintViolationException ex) {
Map<String, String> errors = new HashMap<>();
ex.getConstraintViolations().forEach(cv -> {
String path = cv.getPropertyPath().toString();
String message = cv.getMessage();
errors.put(path, message);
});
return ResponseEntity.badRequest().body(errors);
}
}
Summary:
Use the same @UUID annotation on different parameters.
Specify custom message per usage.
Spring validation will use the message you provide.
Enable @Validated on the controller class to activate method parameter validation.
Optionally handle validation exceptions globally for consistent error responses.
If you want, I can also help you with a full working example including the global exception handler!