Home » Java » Ignore null values while doing validation of input fields

Ignore null values while doing validation of input fields

Posted by: admin October 26, 2017 Leave a comment

Questions:

I have a class with the following elements:

public class Details {
    private String locale;
    private String url;
    private String name;
    private String desc;
    .
    .
    .
}

Now from my client I receive a List. I want to perform some validation over these elements. However it is not necessary that all elements are presents (null is acceptable).

List<Details> detailsList;

Validate.notNull(detailsList);
for(Details details: detailsList) {
    if(details.getLocale() != null) {
        Validate.isTrue(StringUtils.isNotBlank(LocaleUtils.toLocale(details.getLocale()).getVariant()));
    }
    if(details.getUrl() != null) {
        Validate.isTrue(urlValidator.isValid(details.getUrl()));
    }
    //Similarly perform null checks and then do the validation.
}

Is there a better way for me to write this validation instead of writing null checks for each field?

Answers: