Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to not repeat annotations for Bean Validation?

I use Spring MVC with form validating. User entity has field login:

@Pattern(regexp = Constants.LOGIN_PATTERN)
@Size(min = 4, max = 50)
private String login;

But I want to use this annotations with another fields, for ex., with RegisterData.login. So I created another annotation:

@Retention(RetentionPolicy.RUNTIME)
@Target(value = { ElementType.FIELD, ElementType.PARAMETER })
@Pattern(regexp = Constants.LOGIN_PATTERN)
@Size(min = 4, max = 50)
public @interface Login {
}

And now mark fields with it. But that doesn't work. Is it a way to use that type of 'inheritance'? Or should I repeat myself?

like image 913
Feeco Avatar asked Jun 24 '26 18:06

Feeco


1 Answers

You are missing the declaration of the @Login annotation as a constraint, by adding the @Constraint annotation. From the Bean Validation specification:

Composition is done by annotating a constraint annotation with the composing constraint annotations.

Since your composed constraint does not require a validator, you can set the validatedBy property to an empty array.

@Pattern(regexp = Constants.LOGIN_PATTERN)
@Size(min = 4, max = 50)
@Constraint(validatedBy = {})
@Target(value = { ElementType.FIELD, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
public @interface Login {

    String message() default "Incorrect login";

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

    Class<? extends Payload>[] payload() default { };

}
like image 115
Tunaki Avatar answered Jun 26 '26 10:06

Tunaki



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!