2

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;
        }
    }
mKorbel
  • 109,107
  • 18
  • 130
  • 305
user236501
  • 8,300
  • 23
  • 82
  • 119
  • 1
    You may be interested in [JFormattedTextField](http://download.oracle.com/javase/6/docs/api/javax/swing/JFormattedTextField.html). – S.L. Barth Oct 26 '11 at 15:31

3 Answers3

5

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.

matt b
  • 135,500
  • 64
  • 278
  • 339
3
if(id.matches("\\d{5}\\.\\d{2}"))
    return true;
return false;
Danny
  • 7,141
  • 8
  • 42
  • 68
3

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.

Umesh K
  • 12,846
  • 22
  • 85
  • 126