Note that there are some explanatory texts on larger screens.

plurals
  1. POAccess to pre-interpolated bean validation message template in SpringMVC?
    text
    copied!<p>I'm using Spring Validation within a Spring MVC application that delegates validation to Hibernate Validator 5. I'm successfully able to have beans validated and have the messages interpolated by the validator. However, it's important that I also be able to have access to the message template itself, pre-interpolation.</p> <p>For example, in some bean I have validation <code>@Size(min=5,max=15,message="{my.custom.message}"</code>. In a <code>messages.properties</code> file I have entry <code>my.custom.message=test min {min} and max {max}</code>. In my BindingResult, I see the ObjectError with error message "test min 5 and max 15", but I need to look a value up at this point based on the non-interpolated <code>my.custom.message</code> raw value.</p> <p>Can this be done? If it can't out of the box, can someone point me in the right direction for how I might customize spring's LocalValidatorFactoryBean to preserve this?</p> <p><strong>Update</strong></p> <p>I'm looking at extending <code>org.springframework.validation.beanvalidation.SpringValidatorAdapter</code>, and wrapping the <code>getArgumentsForConstraint</code> to automatically append the pre-interpolated message to the returned list of <code>arguments</code>. The notion of exactly what these 'arguments' are and how they're used is unclear to me, but if it's purely used for message interpolation, it seems relatively safe for me to append at the end. Any reason this might not work? Problems it might cause? Better ideas?</p> <p><strong>Solution</strong></p> <p>Didn't find any great solutions other than my 'update' above, so I ended up subclassing <code>LocalValidatorFactoryBean</code> with this:</p> <pre><code>@Override protected Object[] getArgumentsForConstraint(String objectName, String field, ConstraintDescriptor&lt;?&gt; descriptor) { if (null == descriptor) return super.getArgumentsForConstraint(objectName, field, descriptor); Object[] orig = super.getArgumentsForConstraint(objectName, field, descriptor); if (null == orig || orig.length &lt; 1) return new Object[] { descriptor }; Object[] retval = new Object[orig.length+1]; System.arraycopy(orig, 0, retval, 0, orig.length); retval[retval.length-1] = descriptor; return retval; } </code></pre> <p>In subsequent code, I look at the last object in this array and test to see if it's an instance of ConstraintDescriptor. Good enough I suppose.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload