Use your own restrictions for your field. For example, the @StringField annotation will be used.
@Target(ElementType.FIELD) @Constraint(validatedBy = StringFieldValidator.class) @Retention(RetentionPolicy.RUNTIME) public @interface StringField { String message() default "Wrong data of string field"; String messageNotEmpty() default "Field can't be empty"; String messageLength() default "Wrong length of field"; boolean notEmpty() default false; int min() default 0; int max() default Integer.MAX_VALUE; Class<?>[] groups() default {}; Class<?>[] payload() default {}; }
Then do some logic in the StringFieldValidator class. This class is implemented by the ConstraintValidator <A extends Annotation, T> .
public class StringFieldValidator implements ConstraintValidator<StringField, String> { private Boolean notEmpty; private Integer min; private Integer max; private String messageNotEmpty; private String messageLength; @Override public void initialize(StringField field) { notEmpty = field.notEmpty(); min = field.min(); max = field.max(); messageNotBlank = field.messageNotEmpty(); messageLength = field.messageLength(); } @Override public boolean isValid(String value, ConstraintValidatorContext context) { context.disableDefaultConstraintViolation(); if (notEmpty && value.isEmpty()) { context.buildConstraintViolationWithTemplate(messageNotEmpty).addConstraintViolation(); return false; } if ((min > 0 || max < Integer.MAX_VALUE) && (value.length() < min || value.length() > max)) { context.buildConstraintViolationWithTemplate(messageLength).addConstraintViolation(); return false; } return true; } }
Then you can use annotation, for example:
@StringField(notEmpty = true, min = 6, max = 64, messageNotEmpty = "Field can't be empty", messageLength = "Field should be 6 to 64 characters size")
In the end, you will only have one error message, shown in the correct order.
ReaktorDTR
source share