Bean Validation range constraint
Asked Answered
S

4

7

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.

Subjacent answered 13/6, 2016 at 5:24 Comment(2)
You can define range using following annotation. @Max(85) @Min(5) and if you want define custom messages for this validation then you need to create custom constraints. Refer this linkTusk
#5130325Estriol
S
10

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;

   // ...
}
Shit answered 13/6, 2016 at 7:8 Comment(0)
V
2

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>
Verbenaceous answered 13/6, 2016 at 6:41 Comment(0)
V
2

I believe this is the specific annotation you are looking for: https://docs.jboss.org/hibernate/validator/4.1/api/org/hibernate/validator/constraints/Range.html

Example:

@Range(min = 1, max =12)
private String expiryMonth;

This is also a more beneficial annotation because it will work on Strings or Number variants without using two annotations like is the case with @Max/@Min. @Size is not compatible with Integers.

Verbal answered 30/4, 2021 at 15:45 Comment(0)
V
1

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

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

Vigilant answered 17/12, 2019 at 13:8 Comment(1)
I needed it for BigDecimal. This was it :)Suksukarno

© 2022 - 2024 — McMap. All rights reserved.