user236501
user236501

Reputation: 8648

Java textfield decimal validation

How can I validate user input contain only 5 digits with 2 decimal. I am using below code to check 5 digits, but how to check 2 decimal.

if (!id.equals("")) {
        try {
            Integer.parseInt(id);
            if (id.length() <= 5) {
                return true;
            }
        } catch (NumberFormatException nfe) {
            return false;
        }
    }

Upvotes: 2

Views: 4407

Answers (3)

Umesh Kacha
Umesh Kacha

Reputation: 13686

Any validation in Swing can be performed using an InputVerifier.

  1. First create your own input verifier

    public class MyInputVerifier extends InputVerifier {
        public boolean verify(JComponent input) {
            String text = ((JTextField) input).getText();
            try {
                BigDecimal value = new BigDecimal(text);
                return (value.scale() <= Math.abs(2)); 
            } catch (NumberFormatException e) {
                return false;
            }
        }
    }
    
  2. Then assign an instance of that class to your text field. (In fact any JComponent can be verified)

myTextField.setInputVerifier(new MyInputVerifier()); Of course you can also use an anonymous inner class, but if the validator is to be used on other components, too, a normal class is better.

Also have a look at the SDK documentation: JComponent#setInputVerifier.

Upvotes: 3

Danny
Danny

Reputation: 7518

if(id.matches("\\d{5}\\.\\d{2}"))
    return true;
return false;

Upvotes: 3

matt b
matt b

Reputation: 140061

The DecimalFormat class will help you significantly with this. You can check that the user-input can be parsed according to a specific pattern.

The commons-validator library wraps this up in a convenient method call.

Upvotes: 5

Related Questions