Search code examples
javaunivocity

Can univocity execute validators in OR way insted of AND?


I would like to know if there is any way to execute the validators in an OR operator way insted of AND. Currently if the first fails, he doesn't run the other two, however I need him to run them all to return to the user all the respective fixes that he should apply to the file.

I have something like:

@Validate(nullable = false, validators = { NumericValidator.class, LengthValidator.class, DataValidator.class })

I don't create a single validation since I would like to create general validations and just call the specific depending on the field.

Thanks in advance.


Solution

  • I solved building a class like

    import java.util.HashSet;
    import java.util.Set;
    
    import com.univocity.parsers.conversions.Validator;
    
    import co.com.app.constantes.Constants;
    
    public class CustomValidator implements Validator<Object> {
    
    protected Set<Validator<Object>> validators = new HashSet<>();
    
    public CustomValidator() {
        super();
    }
    
    @Override
    public String validate(Object value) {
        Set<String> errors = new HashSet<>();
    
        validators.forEach(validator -> {
            String error = validator.validate(value);
    
            if (error != null) {
                errors.add(error);
            }
        });
    
        if (errors.isEmpty()) {
            return null;
        }
    
        return String.join(Constants.COMMA, errors);
        }
    
    }
    

    Then I create a Validator like

    public class FieldValidator extends CustomValidator {
        public FieldValidator() {
            validators.add(new NumericValidator());
            validators.add(new LengthValidator(1, 11));
        }
    
    }
    

    And in the DTO I used something like

    @Parsed(index = 0)
    @NullString(nulls = { Constants.NULL_VALUE, Constants.EMPTY_VALUE })
    @Validate(nullable = false, validators = { FieldValidator.class })
    private Long field;