M.A.Murali M.A.Murali - 3 months ago 8
Java Question

Amount validation - regular expression in Java

In java class I need regular expression for amount validation with the following conditions:


  1. Maximum price is 9999.99

  2. Minimum amount is 1

  3. Decimal values is optional (Paise is optional) that is 9999 is Valid



I write the following regular expression but it always
return false
for both valid and invalid inputs.

Here's example:

private static final String PRICE_PATTERN = "((/d{1,4})(((//.)(/d{0,2})){0,1}))";

public PriceCheck() {
pattern = Pattern.compile(PRICE_PATTERN);
}

public boolean validate(final String username) {
matcher = pattern.matcher(username);
return matcher.matches(); // always return false;
}

Answer

Use this expression instead:

private static final String PRICE_PATTERN = "((\\d{1,4})(((\\.)(\\d{0,2})){0,1}))";