Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation in swt text

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.

like image 498
Rabin Avatar asked Mar 13 '12 06:03

Rabin


2 Answers

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;
    }
  }
});
like image 105
Tonny Madsen Avatar answered Sep 18 '22 11:09

Tonny Madsen


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.

like image 24
Nick Wilson Avatar answered Sep 19 '22 11:09

Nick Wilson