1. Introduction

Yavi is a Java validation library that allows us to easily and cleanly ensure that our objects are in a valid state.

Yavi is an excellent lightweight choice for object validation within Java applications. It doesn’t rely on reflection or adding additional annotations to the objects being validated, so it can be used entirely separately from the classes we wish to validate. It also emphasizes a type-safe API, ensuring we can’t accidentally define impossible validation rules. In addition, it has full support for any types that we can define in our application, as well as having a large range of predefined constraints to rely on whilst still allowing us to easily define our own where necessary.

In this tutorial, we’re going to have a look at Yavi. We’ll see what it is, what we can do with it, and how to use it.

2. Dependencies

Before using Yavi, we need to include the latest version in our build, which is 0.14.1 at the time of writing.

If we’re using Maven, we can include this dependency in our pom.xml file:

<dependency>
    <groupId>am.ik.yavi</groupId>
    <artifactId>yavi</artifactId>
    <version>0.14.1</version>
</dependency>

At this point, we’re ready to start using it in our application.

3. Simple Validations

Once we’ve got Yavi available in our project, we’re ready to start using it to validate our objects.

The simplest validators that we can build are for simple value types such as String or Integer. Each of the supported types is constructed using a builder class found in the am.ik.yavi.builder package:

StringValidator<String> validator = StringValidatorBuilder.of("name", c -> c.notBlank())
  .build();

This constructs a validator that we can use to validate String instances to ensure they’re not blank. The first parameter to the builder is a name for the value we’re validating, and the second is a lambda that defines the validation rules to apply.

More often though, we want to validate an entire bean, not just a single value. Validators for these are built using the ValidatorBuilder instead, to which we can add multiple rules for different fields:

public record Person(String name, int age) {}
Validator<Person> validator = ValidatorBuilder.of(Person.class)
  .constraint(Person::name, "name", c -> c.notBlank())
  .constraint(Person::age, "age", c -> c.positiveOrZero().lessThan(150))
  .build();

Every constraint() call adds a constraint to our validator for a different field. The first parameter to this is the getter for the field, which must be a method on the type we’re validating. The third parameter is then a lambda for defining the constraint, the same as before. Yavi ensures that this is suitable for the return type of our getter method. For example, we can use notBlank() on a String field but not an integer field.

Once we’ve got our validator, we can use it to validate appropriate objects:

ConstraintViolations result = validator.validate(new Person("", 42));
assertFalse(result.isValid());

This returned ConstraintViolations object tells us whether or not the provided object is valid, and if it’s invalid we can see what the actual violations are:

assertEquals(1, result.size());
assertEquals("name", result.get(0).name());
assertEquals("charSequence.notBlank", result.get(0).messageKey());

Here we can see that the name field is invalid and that the violation is because it shouldn’t be blank.

3.1. Validating Nested Objects

Often our beans that we want to validate have other beans within them, and we want to ensure these are also valid. We can achieve this using the nest() method of our builder instead of the constraint() call:

public record Name(String firstName, String surname) {}
public record Person(Name name, int age) {}

Validator<Name> nameValidator = ValidatorBuilder.of(Name.class)
  .constraint(Name::firstName, "firstName", c -> c.notBlank())
  .constraint(Name::surname, "surname", c -> c.notBlank())
  .build();

Validator<Person> personValidator = ValidatorBuilder.of(Person.class)
  .nest(Person::name, "name", nameValidator)
  .constraint(Person::age, "age", c -> c.positiveOrZero().lessThan(150))
  .build();

Once defined, we can use this the same as before. Now though, Yavi will automatically compose the names of any violations using dotted notation so that we can see exactly what’s happened:

assertEquals(2, result.size());
assertEquals("name.firstName", result.get(0).name());
assertEquals("name.surname", result.get(1).name());

Here we’ve got our two expected violations – one on name.firstName and the other on name.surname. These tell us that the fields in question are nested within the name field of the outer object.

3.2. Cross-Field Validations

In some cases, we can’t validate a single field in isolation. The validation rules might depend on the values of other fields in the same object. We can achieve this using the constraintOnTarget() method, which validates the provided object and not a single field of it:

record Range(int start, int end) {}

Validator<Range> validator = ValidatorBuilder.of(Range.class)
  .constraintOnTarget(range -> range.end > range.start, "end", "range.endGreaterThanStart",
    "\"end\" must be greater than \"start\"")
  .build();

In this case, we’re ensuring that the end value of our range is greater than the start value. When doing this, we need to provide some extra values since we’re effectively creating a custom constraint.

Unsurprisingly, using this validator is the same as before. However, because we’ve defined the constraint ourselves we’ll get our custom values through in the violation:

assertEquals(1, result.size());
assertEquals("end", result.get(0).name());
assertEquals("range.endGreaterThanStart", result.get(0).messageKey());

4. Custom Constraints

Most of the time, Yavi provides us with all the constraints that we need for validating our objects. However, in some cases, we might need something that isn’t covered by the standard set.

We saw earlier an example of writing a custom constraint inline by providing a lambda. We can do similar within our constraint builder to define a custom constraint for any field:

Validator<Data> validator = ValidatorBuilder.of(Data.class)
  .constraint(Data::palindrome, "palindrome",
    c -> c.predicate(s -> validatePalindrome(s), "palindrome.valid", "\"{0}\" must be a palindrome"))
  .build();

Here we’ve used the predicate() method to provide our lambda, as well as giving it a message key and default message. This lambda can do anything we want, as long as it fits the definition of java.util.function.Predicate. In this case, we’re using a function that checks if a string is a palindrome or not.

Sometimes though we might want to write our custom constraint in a more reusable manner, we’re able to do this by creating a class that implements the CustomConstraint interface:

class PalindromeConstraint implements CustomConstraint<String> {
    @Override
    public boolean test(String input) {
        String reversed = new StringBuilder()
          .append(input)
          .reverse()
          .toString();

        return input.equals(reversed);
    }

    @Override
    public String messageKey() {
        return "palindrome.valid";
    }

    @Override
    public String defaultMessageFormat() {
        return "\"{0}\" must be a palindrome";
    }
}

Functionally this is the same as our lambda, only as a class we can more easily reuse it between validators. In this case, we need only pass an instance of this to our predicate() call and everything else is configured for us:

Validator<Data> validator = ValidatorBuilder.of(Data.class)
  .constraint(Data::palindrome, "palindrome", c -> c.predicate(new PalindromeConstraint()))
  .build();

Whichever of these methods we use, we can use the resulting validator exactly as expected:

ConstraintViolations result = validator.validate(new Data("other"));
assertFalse(result.isValid());
assertEquals(1, result.size());
assertEquals("palindrome", result.get(0).name());
assertEquals("palindrome.valid", result.get(0).messageKey());

Here we can see that our field is invalid and that the result includes our defined message key to indicate exactly what was wrong with it.

5. Conditional Constraints

Not all constraints make sense to be applied in all cases. Yavi gives us some tools to configure some constraints to only work in some cases.

One option that we have is to provide a context to the validator. We can define this as any type that we want, as long as it implements the ConstraintGroup interface, though an enum is a very convenient option:

enum Action implements ConstraintGroup {
    CREATE,
    UPDATE,
    DELETE
}

We can then define a constraint using the constraintOnCondition() wrapper to define a constraint that only applies under a particular context:

 Validator<Person> validator = ValidatorBuilder.of(Person.class)
  .constraint(Person::name, "name", c -> c.notBlank())
  .constraintOnCondition(Action.UPDATE.toCondition(),
    b -> b.constraint(Person::id, "id", c -> c.notBlank()))
  .build();

This will always validate that the name field isn’t blank, but will only validate that the id field isn’t blank if we provide a context of UPDATE.

When using this, we need to validate slightly differently, by providing the context along with the value we’re validating:

ConstraintViolations result = validator.validate(new Person(null, "Baeldung"), Action.UPDATE);
assertFalse(result.isValid());

If we want to have even more control, the constraintOnCondition() method can take a lambda that accepts the value being validated and the context, and indicates if the constraint should be applied. This allows us to define whatever conditions we want:

Validator<Person> validator = ValidatorBuilder.of(Person.class)
  .constraintOnCondition((person, ctx) -> person.id() != null,
    b -> b.constraint(Person::name, "name", c -> c.notBlank()))
  .build();

In this case, the name field will only be validated if the id field has a value:

ConstraintViolations result = validator.validate(new Person(null, null));
assertTrue(result.isValid());

6. Argument Validation

One of Yavi’s unique points is its ability to wrap method calls in validation, ensuring that the arguments are valid before calling the method.

Argument validators are all built using the ArgumentsValidatorBuilder builder class. To ensure type safety, this constructs one of 16 possible types, supporting between 1 and 16 arguments to the method.

This is especially useful to wrap the call to the constructor. This allows us to guarantee valid arguments before calling the constructor, instead of constructing a potentially invalid object and validating it afterwards:

Arguments2Validator<String, Integer, Person> validator = ArgumentsValidatorBuilder.of(Person::new)
  .builder(b -> b
    ._string(Arguments1::arg1, "name", c -> c.notBlank())
    ._integer(Arguments2::arg2, "age", c -> c.positiveOrZero())
  )
  .build();

The slightly unusual syntax of _string() and _integer() are so the compiler knows the type to use for each argument.

Once we’ve built our validator, we can then call it passing in all of the appropriate arguments:

Validated<Person> result = validator.validate("", -1);

This result tells us if the arguments were valid, and if not then returns the validation errors:

assertFalse(result.isValid());
assertEquals(2, result.errors().size());
assertEquals("name", result.errors().get(0).name());
assertEquals("charSequence.notBlank", result.errors().get(0).messageKey());
assertEquals("age", result.errors().get(1).name());
assertEquals("numeric.positiveOrZero", result.errors().get(1).messageKey());

If the arguments were all valid then we can instead get back the result of our method – in this case, the constructed object:

assertTrue(result.isValid());
Person person = result.value();

We can also use this same technique to wrap methods on objects as well:

record Person(String name, int age) {
    boolean isOlderThan(int check) {
        return this.age > check;
    }
}
Arguments2Validator<Person, Integer, Boolean> validator = ArgumentsValidatorBuilder.of(Person::isOlderThan)
  .builder(b -> b
    ._integer(Arguments2::arg2, "age", c -> c.positiveOrZero())
  )
  .build();

This will validate the arguments on the method call and only call the method if they’re all valid. In this case, we pass the instance we’re calling the method on as the first argument and then pass all other arguments afterward:

Person person = new Person("Baeldung", 42);
Validated<Boolean> result = validator.validate(person, -1);

As before, if the arguments pass validation then Yavi calls the method and we can access the return value. If the arguments fail validation, it never calls the wrapped method and instead returns the validation errors.

7. Annotation Processing

So far, Yavi has been rather repetitive in several places. For example, we’ve needed to specify the field name and the method reference to get the value, which typically has the same name. Yavi comes with a Java annotation processor that will help here.

7.1. Annotating Fields

We can annotate fields on our objects with the @ConstraintTarget annotation to automatically generate some meta classes:

record Person(@ConstraintTarget String name, @ConstraintTarget int age) {}

These annotations can go on constructor arguments, getters, or fields and it will work the same.

We can then use these generated classes when we’re building our validator:

Validator<Person> validator = ValidatorBuilder.of(Person.class)
  .constraint(_PersonMeta.NAME, c -> c.notBlank())
  .constraint(_PersonMeta.AGE, c -> c.positiveOrZero().lessThan(150))
  .build();

We no longer need to specify both the field name and the corresponding getter. In addition, if we try to use a field that doesn’t exist then this will no longer compile.

Once built, this validator is identical to before and can used the same as before.

7.2. Annotating Arguments

We can also use the same technique for method arguments when using the support for wrapping method calls. In this case, we use the @ConstraintArguments annotation instead, annotating the method or constructor that we plan on validating:

record Person(String name, int age) {
    @ConstraintArguments
    Person {
    }

    @ConstraintArguments
    boolean isOlderThan(int check) {
        return this.age() > check;
    }
}

Yavi generates one meta-class for each method which we can use to generate the validators as before.

Arguments2Validator<String, Integer, Person> validator = ArgumentsValidatorBuilder.of(Person::new)
  .builder(b -> b
    .constraint(_PersonArgumentsMeta.NAME, c -> c.notBlank())
    .constraint(_PersonArgumentsMeta.AGE, c -> c.positiveOrZero())
  )
  .build();

As before, we no longer need to manually specify the argument names or positions. We also no longer need to specify the correct type of constraint – our meta-class has already defined all of this for us.

8. Summary

This was a quick introduction to Yavi. There’s a lot more that can be done with this library, as well as offering good integration with popular frameworks such as Spring. Next time you need a validation library, why not give it a try?

As usual, all of the examples from this article are available over on GitHub.