I would like to validate numbers input in text box.
I want the user to input only integer, decimal in the box between a maximum and minimum values.
How can I make sure of this?
Thank you.
Use a VerifyListener
as this will handle paste, backspace, replace.....
E.g.
text.addVerifyListener(new VerifyListener() {
@Override
public void verifyText(VerifyEvent e) {
final String oldS = text.getText();
final String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
try {
BigDecimal bd = new BigDecimal(newS);
// value is decimal
// Test value range
} catch (final NumberFormatException numberFormatException) {
// value is not decimal
e.doit = false;
}
}
});
You can register a ModifyListener with the text control and use it to validate the number.
txt.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent event) {
String txt = ((Text) event.getSource()).getText();
try {
int num = Integer.parseInt(txt);
// Checks on num
} catch (NumberFormatException e) {
// Show error
}
}
});
You could also use addVerifyListener to prevent certain characters being entered. In the event passed into that method there is a "doit" field. If you set that to false it prevents the current edit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With