Digit Validation With Decimal Values | Filter Pattern | Android Breakdown

We know you do a lot of stuffs to do these kind of things, to validate your digits, price or any decimal values. But no more now.

Yes you heard it right. Here is a simplest solution to do this. We will take an example of validation.

Android Breakdown
EditText to Validate

As you see above an EditText with some required attributes like height and width. Nothing special in it but we will add filter to this EditText programmatically.

Just Paste this Code

EditText editText=findViewById([EditText Id]);

editText.setFilters(new InputFilter[]{
                new InputFilter() {
                    public CharSequence filter(CharSequence source, int start, int end, Spanned destination, int destinationStart, int destinationEnd) {
                        if (end > start) {
                            // adding: filter
                            // build the resulting text
                            String destinationString = destination.toString();
                            String resultingTxt = destinationString.substring(0, destinationStart) + source.subSequence(start, end) + destinationString.substring(destinationEnd);
                            // return null to accept the input or empty to reject it
                            return resultingTxt.matches("^\\-?(\\d{0,3}|\\d{0,3}\\.\\d{0,2})$") ? null : "";
                        // removing: always accept
                        return null;

The above code will restrict the EditText with only 3 digits and after that it will only allow "." and 2 more digits. If you want to change is according to you. Just change here.

return resultingTxt.matches("^\\-?(\\d{0,3}|\\d{0,3}\\.\\d{0,2})$") ? null : "";

There are 4 highlighted digits. First and Second is for the length of digits allowed before "." And the last one is for the length of digits after "." That's it. For be updated Just Subscribe us.