Validate positive integers
Asked Answered
D

9

37

I want to allow only positive integers for number fields including zero. How can I define this validation using JSR 303 ?
I tried

  1. @Min(value=0 message = "msg1") - But it allows float values like 1.2.

  2. @Digits(fraction = 0, integer = 10, message ="msg2") - It accepts negative values.

  3. @Min(value=0, message = "msg1" )
    @Digits(fraction = 0, integer = 10, message ="msg2") - It works fine but sometimes both the messages i.e. msg1 and msg2 are displayed.

Any suggestions?

Thanks!

Dissever answered 15/2, 2012 at 12:15 Comment(7)
Any particular reason you are not using an Integer field?Feline
@Perception: I am working with legacy application and cannot change it right now.Dissever
Use a custom constraint? - nonrepeatable.blogspot.com/2010/05/…Bernice
@Paul: Dont we have a constraint in JSR to handle this?Dissever
BTW, if you use hibernate-validator than you may create custom constraint which combine @Min and @Digits from 3rd option by using @ConstraintComposition(AND). When you add @ReportAsSingleViolation only your custom message will be shown.Cassidycassie
@SlavaSemushin I think that'd be worth of another answerKhajeh
Newer versions support @PositiveOrZero for this purposeIridize
S
18

Looks like you are looking for natural numbers, I think you can use the regex pattern to get the desired output. Something like

@Pattern(regexp = "[\\s]*[0-9]*[1-9]+",message="msg")

Salpingectomy answered 15/2, 2012 at 13:29 Comment(3)
but sadly it cannot be applied for integerEnidenigma
@Enidenigma for integer, isn't @Min the solution? I don't see the point in regexp for an integerKhajeh
I want to have only 2 or more values for an integer that won't work using @Min or @Max right.Purim
R
63

Just use the annotation @Min in your bean:

@Min(value = 0L, message = "The value must be positive")
private Double value;
Ruminant answered 15/1, 2017 at 15:30 Comment(4)
what's the "L" mean in that value?Leggett
"L" means explicit LongNepali
But since it's a Double, it should not be 0.0?Cody
But if you have a look on the annotation, the value is long and in the doc they point that double and float are not supportedFelicita
S
18

Looks like you are looking for natural numbers, I think you can use the regex pattern to get the desired output. Something like

@Pattern(regexp = "[\\s]*[0-9]*[1-9]+",message="msg")

Salpingectomy answered 15/2, 2012 at 13:29 Comment(3)
but sadly it cannot be applied for integerEnidenigma
@Enidenigma for integer, isn't @Min the solution? I don't see the point in regexp for an integerKhajeh
I want to have only 2 or more values for an integer that won't work using @Min or @Max right.Purim
H
12

You can use @Positive that works for the int and its wrappers too (ie Integer). This also will work for the BigInteger as well.

Harken answered 5/12, 2020 at 5:11 Comment(3)
@Positive considers 0 as an invalid value. javaee.github.io/javaee-spec/javadocs/javax/validation/…Feints
You can use it with the @Min annotation and this can provide a solution.Harken
@VijayNandwana There is also @PositiveOrZero. javaee.github.io/javaee-spec/javadocs/javax/validation/…Ladida
C
7

If you use hibernate-validator then you may create a custom constraint which combines @Min and @Digits from the 3rd option by using @ConstraintComposition(AND). When you add @ReportAsSingleViolation, only a custom message will be shown.

Cassidycassie answered 16/1, 2017 at 12:1 Comment(0)
A
4

Its better to use range annotation like below for positive numbers

@Range(min = 0l, message = "Please select positive numbers Only")

For negative numbers

@Range(min = -9223372036854775808l, max = 0l, message = "Please select Negative numbers Only")
Arcograph answered 26/7, 2017 at 9:24 Comment(1)
Why is it better?Maud
B
4

Another kind of solution and in my personal opinion cleaner and easier to read.

@Positive
@Digits(integer = 5, fraction = 0)
Better answered 4/9, 2020 at 14:3 Comment(2)
why did you choose 5 digits in your example?Crampon
@Crampon to check the postal code, but you can introduce the number that you wantInterrelated
H
1

This is an example code from the answer https://mcmap.net/q/413295/-validate-positive-integers above

@Documented
@Min(value=0, message = "add a min msg" )
@Digits(fraction = 0, integer = 10, message ="add a digit msg")
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {})
@ReportAsSingleViolation
public @interface NumberFormatValidator {

    String message() default "invalid number";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

}

It use Constraint composition http://docs.jboss.org/hibernate/validator/4.3/reference/en-US/html_single/#validator-customconstraints-compound and @ReportAsSingleViolation to avoid display both messages

Hayward answered 19/7, 2018 at 15:33 Comment(0)
S
0

Change the data time of your field from int to Integer and a message.properties file to set the message

Example: assuming your fieldName is myNumericField and belongs to a class called Test

  1. Change the datatype:

    • change private int myNumericField; to private Integer myNumericField;

    • Update getters and setters to use/return Integer

  2. Create custom message.properties file. This may appear to be more work but it's a more elegant and scalable solution rather than having the messages hardcoded in your annotations

    • Create a message.properties file under resources directory

    • Edit messages.properties and add the following line

    typeMismatch.Test.myNumericField=Please use integers only

    Remember to change Test and myNumericField for your class and field name

    • Edit your Application Context xml file and add the following tags before the <\beans> tag

    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basenames" value="resources/messages" /> </bean>

Shirelyshirey answered 16/5, 2020 at 23:8 Comment(0)
T
0

Using the following combination solved the issue for me:

  @NotNull
  @Range(min = 1)
  @JsonProperty("end_range")
  private Integer endRange;

Make sure to use Integer class instead of int for @NotNull to work.

Trachytic answered 6/9, 2020 at 16:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.