Reputation: 8648
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
Reputation: 13686
Any validation in Swing can be performed using an InputVerifier.
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; } } }
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
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