/java/

Custom message in annotation validators

2013-03-23 13:07:13

package com.louis.core.validator;

import java.lang.annotation.Documented;
import static java.lang.annotation.ElementType.*;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.*;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;

@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = NotEmptyCustomValidator.class)
@Documented
public @interface NotEmptyCustom {

    String message() default "";

    Class<? >[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}
package com.louis.core.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class NotEmptyCustomValidator implements ConstraintValidator

<notemptycustom, string="">{

    private String message;

    @Override
    public void initialize(NotEmptyCustom constraintAnnotation) {

    }

    @Override
    public boolean isValid(String object, ConstraintValidatorContext constraintContext) {

        message = "Custom message from isValid method";

        constraintContext.disableDefaultConstraintViolation();
        constraintContext.buildConstraintViolationWithTemplate(message).addConstraintViolation();

        return object.equals("") ? false : true;
    }
}