Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.0-flash-001· GoogleHugging Face LMArena Human Preference 140K

I actually dont want to pass the message like so @UUID(message = "User ID must be a…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with o3-mini’s answer.
  1. User

    I actually dont want to pass the message like so @UUID(message = "User ID must be a valid UUID") All i want to do is @UUID and the validator should pick up the requestparam name construct the message like userud must be a valid UUID or applicationdefinitionId should be a valid UUID and so on

  2. Gemini Assistant

    Ok, here's how to modify the custom @ValidUuid annotation solution to automatically use the parameter name in the validation message:

    import jakarta.validation.Constraint;
    import jakarta.validation.ConstraintValidator;
    import jakarta.validation.ConstraintValidatorContext;
    import jakarta.validation.Payload;
    import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
    import org.springframework.web.context.request.RequestContextHolder;
    import org.springframework.web.context.request.ServletRequestAttributes;
    import jakarta.servlet.http.HttpServletRequest;
    
    
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    import java.util.Map;
    import java.util.UUID;
    
    @Target({ElementType.PARAMETER, ElementType.FIELD})
    @Retention(RetentionPolicy.RUNTIME)
    @Constraint(validatedBy = ValidUuidValidator.class)
    public @interface ValidUuid {
    
        String message() default "must be a valid UUID"; //Generic Message No Parameter here
    
        Class<?>[] groups() default {};
    
        Class<? extends Payload>[] payload() default {};
    }
    

    2. The ValidUuidValidator:

    import jakarta.servlet.http.HttpServletRequest;
    import jakarta.validation.ConstraintValidator;
    import jakarta.validation.ConstraintValidatorContext;
    import org.springframework.web.context.request.RequestContextHolder;
    import org.springframework.web.context.request.ServletRequestAttributes;
    
    import java.util.UUID;
    
    public class ValidUuidValidator implements ConstraintValidator<ValidUuid, String> {
    
        @Override
        public boolean isValid(String value, ConstraintValidatorContext context) {
            if (value == null || value.isEmpty()) {
                return true; // Let @NotNull or @NotBlank handle null/empty values
            }
    
            try {
                UUID.fromString(value);
                return true;
            } catch (IllegalArgumentException e) {
                // Get the parameter name from the request
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                HttpServletRequest request = attributes.getRequest();
    
                // Dynamically construct the error message with parameter name
                String parameterName = request.getParameterNames().nextElement();
                String errorMessage = String.format("%s must be a valid UUID", parameterName); //Example : UserId must be a valid UUID
    
                // Disable the default message and add our custom message
                context.disableDefaultConstraintViolation();
                context.buildConstraintViolationWithTemplate(errorMessage)
                    .addConstraintViolation();
    
                return false;
            }
        }
    }
    
    import jakarta.servlet.http.HttpServletRequest;
    import jakarta.validation.ConstraintValidator;
    import jakarta.validation.ConstraintValidatorContext;
    import org.springframework.web.context.request.RequestContextHolder;
    import org.springframework.web.context.request.ServletRequestAttributes;
    
    import java.util.UUID;
    import java.util.Enumeration;
    
    public class ValidUuidValidator implements ConstraintValidator<ValidUuid, String> {
    
        @Override
        public boolean isValid(String value, ConstraintValidatorContext context) {
            if (value == null || value.isEmpty()) {
                return true; // Let @NotNull or @NotBlank handle null/empty values
            }
    
            try {
                UUID.fromString(value);
                return true;
            } catch (IllegalArgumentException e) {
                // Get the parameter name from the request
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                HttpServletRequest request = attributes.getRequest();
    
                Enumeration<String> parameterNames = request.getParameterNames();
                String parameterName = null;
                while (parameterNames.hasMoreElements()) {
                    String name = parameterNames.nextElement();
                    if (value.equals(request.getParameter(name))) {
                        parameterName = name;
                        break;
                    }
                }
    
                if (parameterName == null) {
                    parameterName = "Value"; // Fallback if parameter name not found
                }
    
                // Dynamically construct the error message with parameter name
                String errorMessage = String.format("%s must be a valid UUID", parameterName); //Example : UserId must be a valid UUID
    
                // Disable the default message and add our custom message
                context.disableDefaultConstraintViolation();
                context.buildConstraintViolationWithTemplate(errorMessage)
                        .addConstraintViolation();
    
                return false;
            }
        }
    }
    

    3. Controller Usage:

    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.*;
    
    import java.util.UUID;
    
    @RestController
    @RequestMapping("/api")
    public class MyController {
    
        @GetMapping("/resource")
        public ResponseEntity<String> getResource(
            @RequestParam("userId") @ValidUuid String userId,
            @RequestParam("applicationDefinitionId") @ValidUuid String applicationDefinitionId
        ) {
            //Your Logic
            return ResponseEntity.ok("Resource retrieved");
        }
    }
    

    Explanation:

    1. Get the Parameter Name:

      • Inside isValid, we use RequestContextHolder to get the current HttpServletRequest.
      • Then, we extract the parameter name usingrequest.getParameterNames().nextElement().
    2. Dynamic Error Message:

      • If the UUID format is invalid, we construct a dynamic error message using String.format("%s must be a valid UUID", parameterName);
      • We then use context.disableDefaultConstraintViolation() to suppress the default message and add our custom message.
    3. @ValidUuid Annotation:

      • The message() attribute of the @ValidUuid annotation is now just a generic message (e.g., "must be a valid UUID"). It acts as a fallback if the parameter name cannot be determined for some reason.

    Important Considerations:

    • Thread Safety: RequestContextHolder uses a thread-local variable. This approach is generally safe in typical Spring web applications where requests are handled on separate threads.
    • Error Handling: Make sure you have a global exception handler or a BindingResult in your controller method to handle ConstraintViolationException and return appropriate error responses to the client.
    • Parameter Name Retrieval: The logic to get the parameter name may need adjustments depending on how parameters are passed in your specific use case (e.g., request body parameters, path variables).

    This approach allows you to apply the @ValidUuid annotation without specifying the message each time, while still getting a meaningful, parameter-specific error message when validation fails.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.

Identical first prompt