How to validate EditText in android in real time while entering the value in the input field before button click, like we do with jquery in web

52 views Asked by At

I have to validate the EditText field in android in real time without clicking the button.

I have tried the validation with the requestFocus() method and setErrors() method but it gives the error after the button click. so is there any way?

2

There are 2 answers

0
Philio On

Try using a TextWatcher.

There are Kotlin extension functions for this though, you can probably get away with something like this:

editText.doOnTextChanged { text, start, before, count ->  
    // Validate text
}
0
Rushi Dave On

To Vaildate editText you can use before button click, you can use TextWatcher, It's Use to listen for changes in edittext. Please look into below example:

editText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                // This method is called to notify you that characters within s are about to be replaced with new text with a length of after
                // For example, you might use it to disable a button until a certain number of characters are entered.
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                // This method is called to notify you that somewhere within s, the text has been changed.
                // For example, you might use it to dynamically update a preview as the user types.
            }

            override fun afterTextChanged(s: Editable?) {
                // This method is called to notify you that somewhere within s, the text has been changed.
                // It is called to notify you that somewhere within s, the text has been changed.
                // For example, you might use it to perform validation on user input.
                textView.text = "Entered Text: ${s.toString()}"
            }
        })