Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate positive integers

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!

like image 242
Ajinkya Avatar asked Feb 15 '12 12:02

Ajinkya


People also ask

How do you check if a value is a positive integer?

If the Integer is greater than zero then it is a positive integer.

How do you check if something is a positive integer in Python?

Python Code: n = float(input("Input a number: ")) if n >= 0: if n == 0: print("It is Zero! ") else: print("Number is Positive number. ") else: print("Number is Negative number. ")

How do you check if a number is positive or negative?

If a number is greater than zero, it is a positive number. If a number is less than zero, it is a negative number. If a number equals to zero, it is zero.

How do you validate a number in JavaScript?

Approach: We have used isNaN() function for validation of the textfield for numeric value only. Text-field data is passed in the function and if passed data is number then isNan() returns true and if data is not number or combination of both number and alphabets then it returns false.


2 Answers

Just use the annotation @Min in your bean:

@Min(value = 0L, message = "The value must be positive") private Double value; 
like image 81
Rodrigo Araujo Avatar answered Sep 22 '22 08:09

Rodrigo Araujo


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")

like image 39
jay Avatar answered Sep 24 '22 08:09

jay