I'm creating some custom Validators for univocity parser and I want to add some parameters like this:
public class Size implements Validator<String>
int max;
and then use it like this:
@Parsed
@Validate(nullable = false, validators = Size.class(8) )
private String someString;
I didn't found anything like this or examples with annotations.
Maybe using javax.validation annotations?
Or maybe injecting sizeValidation object created with range limit constructor?
Thanks!
Two options here:
1 - add the annotations on a setter (simple but not reusable:
@Parsed
@Validate(nullable = false)
public void setSomeString(String value){
if(value.length() < 3 || value.length() > 5){
throw new DataValidationException("SomeString can't have length " + value.length());
}
this.someString = value;
}
2 - extend class ValidatedConversion
and use that class on a @Convert
annotation:
public class LengthValidator extends ValidatedConversion {
private int min;
private int max;
public LengthValidator(String... args) {
super(false, false); //not null / not blank
this.min = Integer.parseInt(args[0]);
this.max = Integer.parseInt(args[1]);
}
@Override
protected void validate(Object value) {
super.validate(value); //let super check for null and whatever you need.
String string = value.toString();
if(string.length() < min || string.length() > max){
throw new com.univocity.parsers.common.DataValidationException("Value can't have length " + string.length());
}
}
}
Then add it to your attribute:
@Parsed
@Convert(conversionClass = LengthValidator.class, args = {"3", "5"})
private String someString;
Hope this helps.