Abstract Validators project is a business object validation framework in Java with a more fluent approach then the prevailing JSR-303 Bean Validation standard.
I was originally a .NET/C#/F# stack developer but somehow exposed to Java and OSS projects around Java technology. At the time of writing this project, I was in the process of converting more to JVM based technologies such as Java, Scala and Clojure.
While writing Java projects, I noticed that the frameworks build around JSR-303 have some shortcomings:
- Setting a rule for one
propertyfield against otherpropertiesfields (e.g. Cell phone is required if home phone is null). - Application of different sets of validation rules for different object states (this is arguable, but sometimes necessary).
- Decoupling validation rules from object definition, successfully achieving a
POCOPOJO.
So I want to explore a more fluent approach to solve these shortcomings much like FluentValidation and SpecExpress projects but in Java.
At the root of the project enter
gradle build
at the command line for building.
There will be two usage scenarios for AbstractValidators. Creating a validation class or using an InlineValidator instance.
Suppose that we have a Merchant business object;
public class Merchant {
private String merchantName;
public String getMerchantName() {
return this.merchantName;
}
public void setMerchantName(String merchantName) {
this.merchantName = merchantName;
}
private int numberOfOffices;
public int getNumberOfOffices() {
return numberOfOffices;
}
public void setNumberOfOffices(int numberOfOffices) {
this.numberOfOffices = numberOfOffices;
}
}
We define the rules in a MerchantValidation class which extends from ValidationRules of Merchant;
public class MerchantValidationRules extends ValidationRules<Merchant> {
@Override
public void setRules(){
check(validatedObject.getMerchantId()).isGreaterThanZero()
.when(validatedObject.getNumberOfOffices() > 0)
.withMessage("Merchant ID should be greater than 0 when number of offices is greater than 0.");
check(validatedObject.getMerchantId()).isBetweenIncluding(12, 34)
.when(!validatedObject.getMerchantName().isEmpty())
.withMessage("Merchant Id should be between 12 and 34");
}
}
and finally validate an instance of Merchant object;
Merchant validatedType = new Merchant();
validatedType.setMerchantId(12345567);
validatedType.setNumberOfOffices(12);
validatedType.setMerchantName("Damage Inc.");
MerchantValidationRules rules = new MerchantValidationRules();
ValidationResult validate = rules.validate(validatedType);
TODO: Need to develop further for this sample.