title: Spring ConstraintValidator set custom code/rejected value
body: <p>I created a custom class-level ConstraintValidator that validates a certain field if another field has a specific value. Here's the object:</p>
  
  <pre><code>@ValidRequest
  public class Request {
  
    interface ValidationName {}
  
    @NotBlank(groups = {Default.class})
    private final String fieldName;
  
    @NotBlank(groups = {ValidationName.class})
    @Length(max = 40, groups = {ValidationName.class})
    private final String fieldValue;
  
    // Constructor, getters
  }
  </code></pre>
  
  <p>And the class-level ConstraintValidator:</p>
  
  <pre><code>public class ValidRequestImpl implements
    ConstraintValidator&lt;ValidRequest, Request&gt; {
  
    private Validator validator;
  
    @Autowired
    public ValidRequestImpl (Validator validator) {
      this.validator = validator;
    }
  
    @Override
    public void initialize(ValidRequest constraintAnnotation) {}
  
    @Override
    public boolean isValid(ValidRequest value, ConstraintValidatorContext context) {
      if (!validator.validateProperty(value, "fieldName").isEmpty()) {
        return true;
      }
      if (value.getFieldName().equals("name")) {
        Set&lt;ConstraintViolation&lt;Request&gt;&gt; violations =
          validator.validateProperty(value, "fieldValue", ValidationName.class);
        violations.forEach(violation -&gt; context
          .buildConstraintViolationWithTemplate(violation.getMessage())
          .addPropertyNode("fieldValue")
          .addConstraintViolation());
        context.disableDefaultConstraintViolation();
        return violations.isEmpty();
      }
      return true;
    }
  }
  </code></pre>
  
  <p>This works fine, but the returned errors object isn't very helpful:</p>
  
  <pre><code>"errors": [
    {
      "message": "Please enter a name.",
      "field_name": "request.fieldValue",
      "rejected_value": "com.example.Request@5f017a8c",
      "code": "ValidRequest"
    }
  ],
  </code></pre>
  
  <p>Ideally, I would want the <strong>rejected_value</strong> field to be the actual fieldValue that was passed (in this case empty string), instead of the class-level object. I would also want the <strong>code</strong> field to be the actual annotation that failed (NotBlank), rather than ValidRequest. <em>context.buildConstraintViolationWithTemplate()</em> doesn't appear to have any methods that allow you to change these fields.</p>
  
  <p>How can I accomplish this?</p>