Skip to content

drndivoje/vluent

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Vluent

Simple experimental validation framework (still POC) using fluent interface to define complex validation rules. Java Bean Validation (JSR 380) cannot offer right api to defined complex validation rules such as validation only if the certain condition is satisfied. The second reason is to avoid general overuse of annotations on POJO classes (think about Hibernate) and use more explicit way of defining validation rules.

Usage

Every custom validator should implement Validator interface and validate method which should return ValidatitionResult instance

public class UserNameValidator implements Validator<String>{


    @Override
    public ValidationResult validate(String value) {
        if(value!==null) return SUCCESS;
        return ValidationResult.createError(value + " is null");
    }

ValidationResult is class which contains information on validation error as String.

Applying Validation

For example if you have a User class

public class User {
    private final String name;
    private final LocalDate birthday;
    private final double salary;
    ...

Then to validate User instance call Vluent like

ValidationResult validationResult = Vluent.create()
    .on(user.getName(), new UserNameValidator())
    .on(user.getSalary(), new SalaryValidator())
    .validate();

The validators will apply sequentially. Taking the above example, it means if username is invalid the validation for salary will not be executed and Validation result will contain only information on an invalid username.

Validation Preconditions

In cases of complex validation rules, preconditions could be defined before applying validator

ValidationResult validationResult = Vluent.create()
    .on(user.getName(), new UserNameValidator())
    .when(() -> user.getSalary() > 1000 )
    .then(user.getSalary(), new SalaryValidator())
    .validate();

In this case SalaryValidator will be invoked only for salaries greater then 1000

Releases

No releases published

Packages

No packages published

Languages