Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

microtweak/conditional-validator

Folders and files

NameName
Last commit message
Last commit date

Latest commit

History

63 Commits

Repository files navigation

Conditional Validator

Problem

The constraints of the Bean Validation cannot be turned on/off programmatically or according to any condition of the model object.

The @GroupSequenceProvider annotation from Hibernate Validator (RI) allows you to emulate this feature, however, it is a bit boring and tiring implement a class for each validated model object.

Solution

An extension for Bean Validation 2.0 containing analogous annotations for each constraint. For example, if you want to apply @NotNull conditionally use @NotNullWhen(expression = "")

Currently, the constraint expression is provided by Commons Jexl. All provided expression must return a Boolean (true/false).

Whenever the expression returns true, Conditional Validator delegates to the provider (Hibernate Validator or Apache BVal) the corresponding validation. For example, when the @NotNulWhen expression is true, ConditionalValidator tells the provider to validate as @NotNull.

Usage

  1. Add dependency to pom.xml
<!-- If you use Hibernate Validator (RI) -->
<dependency>
 <groupId>com.github.microtweak</groupId>
 <artifactId>conditional-validator-hv</artifactId>
 <version>${conditional-validator.version}</version>
</dependency>
<!-- If you use Apache BVal -->
<dependency>
 <groupId>com.github.microtweak</groupId>
 <artifactId>conditional-validator-bval</artifactId>
 <version>${conditional-validator.version}</version>
</dependency>
  1. Add annotations Conditional Validator
@ConditionalValidate // Enable conditional validation on this class
public class User {
 private boolean notifyByEmail;
 @EmailWhen(expression = "notifyByEmail") // Add the conditional constraint and set the expression
 private String email;
 
 // Getters and Setters
}

About

An extension package for Bean Validation 2.0 that adds conditional validations

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

AltStyle によって変換されたページ (->オリジナル) /