4. You wrote a custom validator but it always passes validation even for invalid data. Which of these is the most likely cause?
medium
A. The annotation interface is missing the @Target annotation
B. The isValid method always returns true regardless of input
C. The validator class does not implement ConstraintValidator
D. The message() method in the annotation returns an empty string
Solution
Step 1: Understand the role of isValid method
This method contains the validation logic and must return true only for valid inputs.
Step 2: Identify why validation always passes
If isValid always returns true, invalid data will pass unchecked.
Final Answer:
The isValid method always returns true regardless of input -> Option B
Quick Check:
isValid controls validation result; always true means always pass [OK]
Hint: Check isValid method return values first when validation fails [OK]
Common Mistakes:
Forgetting to implement ConstraintValidator interface
Missing @Target causes compile warnings but not always validation failure
Empty message() affects error text, not validation logic
5. You want to create a custom validator annotation @StartsWith that checks if a string starts with a given prefix. Which combination of elements is required to implement this correctly?
hard
A. An annotation interface with a String prefix() method, a validator class implementing ConstraintValidator<StartsWith, String>, and overriding isValid to check the prefix
B. An annotation interface with int length(), a validator class implementing Validator, and overriding validate to check length
C. A class annotated with @Component that implements ConstraintValidator without an annotation interface
D. An annotation interface with String suffix(), a validator class implementing ConstraintValidator<EndsWith, String>, and overriding isValid to check suffix
Solution
Step 1: Define the annotation interface with a prefix parameter
The annotation must declare a method String prefix() to accept the prefix value.
Step 2: Implement the validator class correctly
The validator class must implement ConstraintValidator<StartsWith, String> and override isValid to check if the string starts with the given prefix.
Final Answer:
An annotation interface with a String prefix() method, a validator class implementing ConstraintValidator<StartsWith, String>, and overriding isValid to check the prefix -> Option A