-
Sub-task
-
Resolution: Unresolved
-
Major
-
2.1.1.Final
Some constraints need to have fields (attributes). For example, the URL constraint needs three fields : a protocol, a host, and a port :
constraint-add-field --named protocol --type String --targetConstraint URL constraint-add-field --named host --type String --targetConstraint URL constraint-add-field --named port --type String --targetConstraint URL
This will add the three attributes to the existing constraint URL :
@Documented
@Constraint(validatedBy = URLValidator.class)
@Target( { METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@ReportAsSingleViolation
public @interface URL {
String message() default "{org.mycompany.myproject.constraints.URL.message}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
String protocol() default "";
String host() default "";
int port() default -1;
@Target( { METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
public @interface List {
URL[] value();
}
}
But it will also add the three attributes to the implementation : attributes and initialize method :
public class URLValidator implements ConstraintValidator<URL, String> { private String protocol; private String host; private int port; @Override public void initialize(URL url) { this.protocol = url.protocol(); this.host = url.host(); this.port = url.port(); } @Override public boolean isValid(String value, ConstraintValidatorContext context) { return false; } }