Workbook 3.3
In this workbook, you will create a custom constraint annotation.
Task 1
Add the custom Age
annotation:
- It is applied at the
FIELD
level. - It is retained at
RUNTIME
. - It carries a default message of
"INVALID AGE"
;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Age {
String message() default "INVALID AGE";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Task 2
Apply the annotation on the dateOfBirth
field, and override the default message.
@Age(message = "Must be at least 18")
Task 3
As it stands, the annotation isn't connected to any constraint validation logic. Create an AgeValidator
class, and specify that Age
is a @Constraint
that's connected to it.
@Constraint(validatedBy = AgeValidator.class)
Inside AgeValidator.java
, implement the validation logic using the code below. See the cheat sheet if you forgot how to set up a validator.
long diff = new Date().getTime() - value.getTime(); int age = (int) (TimeUnit.MILLISECONDS.toDays(diff) / 365);
Make the necessary changes inside the HTML to achieve the following output.
Task 4
The username cannot contain any special characters $ % # @ ^ *
or uppercase letters. Define another annotation named Username
. Once again, the annotation will be:
- applied at the
FIELD
level. - retained at
RUNTIME
. - carry a default message of
"INVALID USERNAME"
;
Task 5
Apply the annotation on the username
field, and override the default messsage.
@Username(message = "Cannot contain special characters or uppercase characters ")
Task 6
Define the annotation as a @Constraint
that's connected to the UsernameValidator
class. Use the following code to Implement the validation logic:
import java.util.regex.Matcher; import java.util.regex.Pattern; Pattern pattern = Pattern.compile("[^a-z0-9 ]"); Matcher matcher = pattern.matcher(value); boolean badCharacters = matcher.find(); //false if characters are a-z or 0-9
Make the necessary changes to achieve the following output.
Test Case 1
Test Case 2
Task 7
Place the annotation and validator classes in a single folder called validation
.