Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVAFx TextField Validation Decimal value

Tags:

java

regex

javafx

I am try to restrict the textfield for decimal numbers, I already found the solution for integer number validation here, but the problem is that I am not able to convert the following code for decimal numbers, something like 324.23, 4.3, 4, 2, 10.43. (only 1 decimal point allow).

 vendorList_textField_remaining.textProperty().addListener(new ChangeListener<String>() {
        @Override
        public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
            if (!newValue.matches("\\d*")) {
                vendorList_textField_remaining.setText(newValue.replaceAll("[^\\d||.]", ""));
            }
        }
    });

I am also looking for alternative solutions. Thanks.

like image 350
Faraz Sultan Avatar asked Dec 23 '22 23:12

Faraz Sultan


2 Answers

I have met the same situation. I think I have found the a solution to this question. The regex has to been replaced by a new one and a little changes by setText. For now it works well. The code follows:

vendorList_textField_remaining.textProperty().addListener(new ChangeListener<String>() {
        @Override
        public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
            if (!newValue.matches("\\d*(\\.\\d*)?")) {
                vendorList_textField_remaining.setText(oldValue);
            }
        }
    });
like image 146
Xu Li Avatar answered Dec 28 '22 06:12

Xu Li


Thanks for help. I have solved my problem with solution (1).

vendorList_textField_remaining.textProperty().addListener(new ChangeListener<String>() {
    @Override
    public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
        if(!newValue.matches("\\d*(\\.\\d*)?")) {
            vendorList_textField_remaining.setText(oldValue);
        }
    }
});
like image 38
Mohammad Kamruzzaman Avatar answered Dec 28 '22 05:12

Mohammad Kamruzzaman