Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bean Validation range constraint

I need to implement range constraints on Entity data fields:

@Entity
@Table(name = "T_PAYMENT")
public class Payment extends AbstractEntity {

    //....

    //Something like that
    @Range(minValue = 80, maxValue = 85)
    private Long paymentType;

}

I already created validating service, but have to implement many of these cases.

I need the app to throw exception if the inserted number is out of range.

like image 736
J-Alex Avatar asked Jun 13 '16 05:06

J-Alex


People also ask

What is Bean Validation constraints?

The Bean Validation model is supported by constraints in the form of annotations placed on a field, method, or class of a JavaBeans component, such as a managed bean. Constraints can be built in or user defined. User-defined constraints are called custom constraints.

What does @NotNull annotation mean in bean property?

The @NotNull Annotation is, actually, an explicit contract declaring the following: A method should not return null. A variable (like fields, local variables, and parameters) cannot should not hold null value.

What is constraint validation in Java?

constraints Description. Contains all the Bean Validation provided constraints also called built-in constraints. These constraints do not cover all functional use cases but do represent all the fundamental blocks to express low level constraints on basic JDK types.


3 Answers

You need Hibernate Validator (see documentation)

Hibernate Validator

The Bean Validation reference implementation.

Application layer agnostic validation Hibernate Validator allows to express and validate application constraints. The default metadata source are annotations, with the ability to override and extend through the use of XML. It is not tied to a specific application tier or programming model and is available for both server and client application programming. But a simple example says more than 1000 words:

public class Car {

   @NotNull
   private String manufacturer;

   @NotNull
   @Size(min = 2, max = 14)
   private String licensePlate;

   @Min(2)
   private int seatCount;

   // ...
}
like image 113
Raman Sahasi Avatar answered Oct 11 '22 03:10

Raman Sahasi


With hibernate-validator dependency you can define range check

@Min(value = 80)
@Max(value = 85)
private Long paymentType;

In pom.xml add below dependency

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>{hibernate.version}</version>
    </dependency>
like image 43
Saravana Avatar answered Oct 11 '22 01:10

Saravana


For integer and long you can use @Min(value = 80) @Max(value = 85)

For BigDecimal @DecimalMin(value = "80.99999") @DecimalMax(value = "86.9999")

like image 31
Syam Dorjee Avatar answered Oct 11 '22 03:10

Syam Dorjee