Set Button enabled if Regex phone number is valid Android

Viewed 43

How to enable a button if regex expression is valid for number , here is my code in ViewModel

 private val changeButtonAvailable = MutableLiveData(false)

fun changeNumbers() {
        val regex = "(\\+7|8)[0-9]{10}".toRegex()
        if (regex.pattern.length == NUMBER_LENGTH){
            changeButtonAvailable.value = true
        }
        changeButtonAvailable.value = true

    }



fun formatNumber(mobile: String): String {
        val regex = "(\\+7|8)[0-9]{10}"
        val pattern = Pattern.compile(regex)
        val matcher = pattern.matcher(mobile)
        return if (matcher.matches()) {
            val firstNumber = matcher.group(1)
            changeButtonAvailable.value = firstNumber?.length == NUMBER_LENGTH
            "$firstNumber"
        } else {
            mobile
        }
    }

I want make Request +7999999999 not like +7 999 999 999 99

how to make Enable button ? above methods not working for me. thank advance

1 Answers

You should use this regex instead "+7[0-9]{9}". The prefix number is excluded from the count that you mention. Removed the extra slash and 8 length option. You can find appropriate screenshot attached here that verifies this.

You can use this website for testing regex. https://regex101.com/

enter image description here

Related