Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConstraintValidatorContext to define custom error messages

I want to create custom email validator using annotations. This solution was useful while creating the validator. Here's the 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 the 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 the project, but, when I click submit on the registration form, while the email format is not valid I have the following exception :

Request processing failed; nested exception is javax.validation.ConstraintViolationException: Validation failed for classes [...] during persist time for groups [javax.validation.groups.Default, ]

error 500

the exception was as excpected, But instead of showing a 500 error, I would like to see an error message explaning what's wrong. So, I think I have to use ConstraintValidatorContext to define custom error messages. But, I don't know how to do it. Any ideas please ?

like image 251
Najoua Avatar asked Mar 22 '26 07:03

Najoua


1 Answers

You should use @ControllerAdvice and handle validation exceptions there with @ExceptionHandler(MethodArgumentNotValidException.class) for example.

like image 198
Ivan Avatar answered Mar 24 '26 19:03

Ivan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!