项目作者: microtweak

项目描述 :
An extension package for Bean Validation 2.0 that adds conditional validations
高级语言: Java
项目地址: git://github.com/microtweak/conditional-validator.git
创建时间: 2019-08-01T00:15:35Z
项目社区:https://github.com/microtweak/conditional-validator

开源协议:MIT License

下载


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
  1. <!-- If you use Hibernate Validator (RI) -->
  2. <dependency>
  3. <groupId>com.github.microtweak</groupId>
  4. <artifactId>conditional-validator-hv</artifactId>
  5. <version>${conditional-validator.version}</version>
  6. </dependency>
  7. <!-- If you use Apache BVal -->
  8. <dependency>
  9. <groupId>com.github.microtweak</groupId>
  10. <artifactId>conditional-validator-bval</artifactId>
  11. <version>${conditional-validator.version}</version>
  12. </dependency>
  1. Add annotations Conditional Validator
  1. @ConditionalValidate // Enable conditional validation on this class
  2. public class User {
  3. private boolean notifyByEmail;
  4. @EmailWhen(expression = "notifyByEmail") // Add the conditional constraint and set the expression
  5. private String email;
  6. // Getters and Setters
  7. }