1

I need to set validation for a edittext view should allow two numeric values and two decimal values. example: 22.32

Please let me know how to do this validation

Thanks in advance

praveenb
  • 10,549
  • 14
  • 61
  • 83

2 Answers2

7

Try this out. I suck at regex so it may not be the best, but give it a try.

    EditText text = new EditText(this);
    InputFilter[] filters = new InputFilter[1];
    filters[0] = new InputFilter() {
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            if (end > start) {
                String destTxt = dest.toString();
                String resultingTxt = destTxt.substring(0, dstart) + source.subSequence(start, end) + destTxt.substring(dend);
                if (!resultingTxt.matches("^\\d(\\d(\\.\\d{0,2})?)?")) {
                    return "";
                }
            }
        return null;
        }
    };
    text.setFilters(filters);
Aleadam
  • 40,203
  • 9
  • 86
  • 108
1
boolean isValid=<EditText Variable>.getText().toString().matches("\\d{2}\\.\\d{2}");

Put this method in a onClickListener and I guess you will be good to go.

chaitanya
  • 1,591
  • 2
  • 24
  • 39
  • When I tried that regex, it did not match it because it required the dot regardless of the number of digits. Using `\\.?` was not good enough either because it would allow for digits with no dot. Take a look at the alternative regex I posted. And I assume you meant `onKeyListener` instead. – Aleadam Apr 21 '11 at 01:44
  • @Aleadam well he is trying to validate after the input has been entered so I wrote onClick and this is just for the case where you want a number like 23.45. The expression \\. means you are using the literal . A normal . in regex means match any character. – chaitanya Apr 21 '11 at 03:15
  • I understand the meaning of the `\\.` expression. I was only comparing `\\.` to `\\.?` (i.e., forcing the dot presence vs an optional dot). It is OK to use your expression if you validate the final string, but not if you validate it as it is being typed. – Aleadam Apr 21 '11 at 04:27
  • @Aleadam i gave the expression only to evaluate the final string, not as it is typed. – chaitanya Apr 21 '11 at 05:31
  • Hi chaitanya it worked for me, thank you very much... for ur help :) – praveenb Apr 22 '11 at 19:28