hibernate - Building Dynamic ConstraintViolation Error Messages -
i've written validation annotation implemented custom constraintvalidator
. want generate specific constraintviolation
objects use values computed during validation process during message interpolation.
public class customvalidator implements constraintvalidator<customannotation, validatedtype> { ... @override public boolean isvalid(validatedtype value, constraintvalidatorcontext context) { // figure out value not valid. // now, want add violation error message requires arguments. } }
a hypothetical error message in message source:
customannotation.notvalid = supplied value {value} not valid because {reason}.
the context passed isvalid
method provides interface building constraint violation, , adding context. however, can't seem figure out how use it. according documention version i'm using, can add bean , property nodes violation. these additional details can specify violation definition, don't understand how might map parameters in error message.
million dollar question: how can pass dynamic parameters validation error messages using custom validator? fill in {value}
, {reason}
fields using constraintvalidatorcontext
's interface building violations.
obtaining instance of message source , interpolating message within custom validator not option - messages coming out of validation interpolated no matter what, , interpolating internally result in messages being interpolated twice, potentially annihilating escaped single quotes or other characters special meanings in message definitions file.
that's not possible standardized bean valiation api, there way in hibernate validator, bv reference implementation.
you need unwrap constraintvalidatorcontext
hibernateconstraintvalidatorcontext
gives access addexpressionvariable()
method:
public class myfuturevalidator implements constraintvalidator<future, date> { public void initialize(future constraintannotation) {} public boolean isvalid(date value, constraintvalidatorcontext context) { date = gregoriancalendar.getinstance().gettime(); if ( value.before( ) ) { hibernateconstraintvalidatorcontext hibernatecontext = context.unwrap( hibernateconstraintvalidatorcontext.class ); hibernatecontext.disabledefaultconstraintviolation(); hibernatecontext.addexpressionvariable( "now", ) .buildconstraintviolationwithtemplate( "must after ${now}" ) .addconstraintviolation(); return false; } return true; } }
the reference guide has more details.
Comments
Post a Comment