How to set Edittext view allow only two numeric va

2019-01-20 06:19发布

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

2条回答
来,给爷笑一个
2楼-- · 2019-01-20 06:45
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.

查看更多
再贱就再见
3楼-- · 2019-01-20 07:04

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);
查看更多
登录 后发表回答