user3919727
user3919727

Reputation: 343

Double validation

I have the below json property which holds the numeric value

 "creditLimit": "844500" 

which has the following conditions:

  1. Should not exceed 10 digits
  2. Must be a whole number, should not have decimals

Below are example valid inputs for which I want to throw a validation error message back to the user, saying invalid entry:

45500.00
9876543210

Example invalid inputs:

540.50
98765432109

When I tried

 Double.valueOf(ent.creditLimit).intValue() 

the final value alters, looks like it round off the value.

I do not want to keep the decimals.

How to retain the exact value? Thanks in advance

Upvotes: 0

Views: 315

Answers (2)

xerx593
xerx593

Reputation: 13261

  1. Ensure there is a javax.validation implementation in your classpath/runtime.
  2. In your JSON-Pojo, then:

    @javax.validation.constraints.Pattern(regexp = "^\\d{1,10}$")
    private String creditLimit;
    

Allows only numerical strings of length 1 to 10. Throws exception otherwise.

Upvotes: 1

brso05
brso05

Reputation: 13232

You could either use a regular expression to validate or you could parse as a BigDecimal then use intValueExact():

BigDecimal bd = new BigDecimal("540.50");
try
{
    bd.intValueExact();
    //number is a whole number
} catch(ArithmeticException e)
{
    //number is not a whole number
}

Upvotes: 2

Related Questions