Skip to content Skip to sidebar Skip to footer

How To Prevent User From Entering Zero As An Input?

I'm trying to add input validation to a set of three EditTexts that the user enter numeric values into. The problem I'm facing is for the calculation to work the user can't enter z

Solution 1:

Just add android:digits="123456789" to the EditText in XML. This way the user won't be able to input 0

[EDIT]

However, if you want to avoid the user from entering 0 only at the beginning, then use this:

code_text.addTextChangedListener(newTextWatcher(){
            publicvoidonTextChanged(CharSequence s, int start, int before, int count)
            {
                if (code_text.getText().toString().matches("^0") )
                {
                    // Not allowed
                    Toast.makeText(context, "not allowed", Toast.LENGTH_LONG).show();
                    code_text.setText("");
                }
            }
            @OverridepublicvoidafterTextChanged(Editable arg0) { }
            @OverridepublicvoidbeforeTextChanged(CharSequence s, int start, int count, int after) {}
        }); 

Solution 2:

Try this instead

if(getoffsetlength.trim().equalsIgnoreCase("0"){
 Toast.makeText(this, "Enter number greater than 0!", Toast.LENGTH_SHORT).show();
 return;
}

Solution 3:

you can also use below code

int PreviousLen;
        boolean keyDel; 
        etActLoginMobNo.addTextChangedListener(newTextWatcher() {
        @OverridepublicvoidbeforeTextChanged(CharSequence s, int start, int count, int after) {
            mPreviousLen = s.length();
        }

        @OverridepublicvoidonTextChanged(CharSequence s, int start, int before, int count) {

        }

        @OverridepublicvoidafterTextChanged(Editable s) {
            keyDel = mPreviousLen > s.length();
            if(!keyDel){
                if (etActLoginMobNo.getText().toString().startsWith("0")) {
                    etActLoginMobNo.setText("");
                    Toast.makeText(context, R.string.enter_mobile_no_without_zero, Toast.LENGTH_SHORT).show();
                }
            }
        }

Post a Comment for "How To Prevent User From Entering Zero As An Input?"