Home » Android » How to validate an EditText in a range of numbers or do nothing if it's a text?

How to validate an EditText in a range of numbers or do nothing if it's a text?

Posted by: admin November 1, 2017 Leave a comment

Questions:

Example:

  • if i input “HELLO” the EditText should contain “HELLO”.
  • if I input “10” the EditText should validate between range (0-20).

How can I make this in a single EditText?

Answers:

In your EditText TextWatcher add this code:

 String text = editText.getText().toString();

    int lenght = text.length();
    boolean containtDigit = false;
    boolean containChar;

    // if there are any character metches return true
    containChar = text.matches(".*[a-zA-Z]+.*");

    // check for digits
    for (int i = 0; i < lenght; i++) {
        if (text.charAt(i) >= '0' && text.charAt(i) <= '9') {
            containtDigit = true;
            break;
        }
    }

    if (containChar && containtDigit) {
        return editText.setMaxLenght(/*your max length for string*/); // is string 
    } else if (containtDigit && !containChar) { 
           editText.setMaxLenght(20);               
           retutn // is digit and must 20 character
    }