84

I want to do some domain validation. In my object I have one integer.

Now my question is: if I write

@Min(SEQ_MIN_VALUE)
@Max(SEQ_MAX_VALUE)
private Integer sequence;

and

 @Size(min = 1, max = NAME_MAX_LENGTH)
 private Integer sequence;

If it's an integer which one is proper for domain validation?
Can anybody explain me what is the difference between them?

Thanks.

informatik01
  • 16,038
  • 10
  • 74
  • 104
JOHND
  • 2,597
  • 6
  • 27
  • 35
  • What is your reason for using different constants? Why using NAME_MAX_LENGTH instead of the above used SEQ_MAX_VALUE in this question? If there is non, I would recommend using the same as to not distract from the core of the question. – Simeon Feb 01 '21 at 10:36

3 Answers3

159

@Min and @Max are used for validating numeric fields which could be String(representing number), int, short, byte etc and their respective primitive wrappers.

@Size is used to check the length constraints on the fields.

As per documentation @Size supports String, Collection, Map and arrays while @Min and @Max supports primitives and their wrappers. See the documentation.

okocian
  • 488
  • 4
  • 11
Sunil Chavan
  • 2,934
  • 4
  • 25
  • 24
25
package com.mycompany;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class Car {

    @NotNull
    private String manufacturer;

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

    @Min(2)
    private int seatCount;

    public Car(String manufacturer, String licencePlate, int seatCount) {
        this.manufacturer = manufacturer;
        this.licensePlate = licencePlate;
        this.seatCount = seatCount;
    }

    //getters and setters ...
}

@NotNull, @Size and @Min are so-called constraint annotations, that we use to declare constraints, which shall be applied to the fields of a Car instance:

manufacturer shall never be null

licensePlate shall never be null and must be between 2 and 14 characters long

seatCount shall be at least 2.

Ajinkya
  • 22,324
  • 33
  • 110
  • 161
Rahul Agrawal
  • 8,913
  • 18
  • 47
  • 59
  • 2
    OP is asking about `@Size` applied to an `Integer`, I think that's the point of his confusion. Is it even legal to apply it to an integer? It might have the semantics similar to those in an RDMS -- digit count. – Marko Topolnik Jun 25 '12 at 12:46
  • can u pls tell me difference between @size(max = value ) and @min(value) @max(value) – JOHND Jun 25 '12 at 13:03
8

From the documentation I get the impression that in your example it would be intended to use:

@Range(min= SEQ_MIN_VALUE, max= SEQ_MAX_VALUE)

Checks whether the annotated value lies between (inclusive) the specified minimum and maximum. Supported data types:

BigDecimal, BigInteger, CharSequence, byte, short, int, long and the respective wrappers of the primitive types

Simeon
  • 748
  • 1
  • 9
  • 26