java - ConstraintValidatorContext to define custom error messages -
i want create custom email validator using annotations. this solution useful while creating validator. here's annotation :
@target({elementtype.method, elementtype.field, elementtype.annotation_type, elementtype.constructor, elementtype.parameter}) @retention(retentionpolicy.runtime) @constraint(validatedby = {commonsemailvalidator.class}) @documented @reportassingleviolation public @interface exemailvalidator { string message() default " {org.hibernate.validator.constraints.email.message}"; class<?>[] groups() default {}; class<? extends payload>[] payload() default {}; @target({elementtype.method, elementtype.field, elementtype.annotation_type, elementtype.constructor, elementtype.parameter}) @retention(retentionpolicy.runtime) @documented public @interface list { exemailvalidator[] value(); } }
and here's class commonsemailvalidator :
public class commonsemailvalidator implements constraintvalidator<exemailvalidator, string> { private static final boolean allow_local = false; private emailvalidator realvalidator = emailvalidator.getinstance(allow_local); @override public void initialize(exemailvalidator email) { // todo auto-generated method stub } @override public boolean isvalid(string email, constraintvalidatorcontext constraintvalidatorcontext) { if( email == null ) return true; return realvalidator.isvalid(email); } }
i run project, but, when click submit on registration form, while email format not valid have following exception :
request processing failed; nested exception javax.validation.constraintviolationexception: validation failed classes [...] during persist time groups [javax.validation.groups.default, ]
the exception excpected, instead of showing 500 error, see error message explaning what's wrong. so, think have use constraintvalidatorcontext define custom error messages. but, don't know how it. ideas please ?
you should use @controlleradvice
, handle validation exceptions there @exceptionhandler(methodargumentnotvalidexception.class)
example.
Comments
Post a Comment