Clarification Needed on Using forEachIfPresent for Null/Empty Checks and Cross-Field Validation #410
-
I have these 2 interfaces: interface User {
@Nullable List<String> emails();
@Nullable List<PassKey> passKeys();
}
interface PassKey {
byte[] id();
User user();
} So, first I try to validate the emails a user can have like this: Validator<User> userValidator = ValidatorBuilder.<User>of()
.forEachIfPresent(User::emails,"emails", b->b._string(e->e,"email", CharSequenceConstraint::email))
.build(); This compiles, but I am not sure (and there is no javadocs!) what "forEachIfPresent" means. Does it means that the validation will work if the emails list itself is not empty/null only, or does it mean it will skip NULL/empty email string elements? Because I need both - the validation should only happen if the list of emails is not null/empty, but there should be no NULLS or empty string emails inside. How do I do that? Also I do not like the "e->e" stuff. I know I could use The second validation is more complicated - I want to make sure that passkeys in User (if there are any) always refer back the owning user, e.g. passkey.user() points back to the owning user. I looked at "cross-field validation" section in the docs, still no idea how to this - any clue? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
https://yavi.ik.am/#constraints-on-elements-in-a-collection-map-array
If list is not null, validation will be run on each element, but if it is empty, nothing will happen a s a result. https://yavi.ik.am/#built-in-constraints
Use
Something like this? Validator<User> userValidator = ValidatorBuilder.<User>of()
.forEachIfPresent(User::emails, "emails", b -> b._string(e -> e, "email", c -> c.notEmpty().email()))
.constraintOnTarget(new CustomConstraint<>() {
@Override
public String defaultMessageFormat() {
return "tbd";
}
@Override
public String messageKey() {
return "tbd";
}
@Override
public boolean test(User user) {
List<PassKey> passKeys = user.passKeys();
if (passKeys != null) {
return passKeys.stream()
.filter(passKey -> !Objects.equals(passKey.user(), user))
.findAny()
.isEmpty();
}
return true;
}
}, "passKeys")
.build(); |
Beta Was this translation helpful? Give feedback.
-
Thanks @making ,let me try that .. will post with any additional question. Closing this one now |
Beta Was this translation helpful? Give feedback.
IfPresent
means if the fields is not null.https://yavi.ik.am/#constraints-on-elements-in-a-collection-map-array
If list is not null, validation will be run on each element, but if it is empty, nothing will happen a s a result.
https://yavi.ik.am/#built-in-constraints
Most built-in constraints, except
notXXXX
, do not validate fields if they are null. All examples include the case where the fields are null.