android kotlin - EditText phone number validation

Android Kotlin - EditText Phone Number Validation

This code demonstrates real-time phone number validation for an EditText in an Android application written in Kotlin. It utilizes a TextWatcher to monitor user input and provides feedback on the validity of the phone number.

Here's a breakdown of the code:

  1. MainActivity.kt:

    • This file defines the main Activity class responsible for handling the UI and user interaction.
    • It retrieves an EditText reference with the ID "editText" from the layout file.
    • The onCreate method sets up a TextWatcher for the EditText.
  2. TextWatcher:

    • This anonymous class implements the TextWatcher interface, which has three methods:
      • beforeTextChanged (not used in this example)
      • onTextChanged: This method is called whenever the text in the EditText changes. It checks if the entered text is a valid phone number using the isValidPhoneNumber extension function. If not, it sets an error message on the EditText. Otherwise, it clears any existing error.
      • afterTextChanged (not used in this example)
  3. isValidPhoneNumber extension function:

    • This function is a concise way to validate phone number input.
    • It checks if the input is not null or empty and then uses the built-in Patterns.PHONE matcher to see if the text matches a generic phone number format. It returns true if the input is valid and false otherwise.
  4. activity_main.xml:

    • This file defines the layout of the main activity screen.
    • It contains an EditText widget with the ID "editText" configured for phone number input using the inputType attribute.

Summary

This code provides a simple yet effective way to validate phone number input in an Android app. The TextWatcher ensures real-time feedback for the user, improving the user experience. The use of an extension function keeps the validation logic clean and reusable. While Patterns.PHONE offers basic phone number validation, keep in mind that for stricter validation based on specific country formats, you might need a more advanced library or custom logic.


MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Patterns
import android.widget.EditText


class MainActivity : Activity() {
    private lateinit var editText:EditText

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // get the widgets reference from XML layout
        editText = findViewById(R.id.editText)

        // add text changed listener for edit text
        editText.addTextChangedListener(object: TextWatcher{
            override fun beforeTextChanged(p0: CharSequence?,
                                           p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?,
                                       p1: Int, p2: Int, p3: Int) {
                // check inputted characters is a valid phone number or not
                if (p0.isValidPhoneNumber()){
                    editText.error = null
                }else{
                    editText.error = "Invalid phone number."
                }
            }

            override fun afterTextChanged(p0: Editable?) { }
        })
    }
}


// extension function to validate edit text inputted phone number
fun CharSequence?.isValidPhoneNumber():Boolean{
    return !isNullOrEmpty() && Patterns.PHONE.matcher(this).matches()
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#DCDCDC"
    android:padding="32dp">

    <EditText
        android:id="@+id/editText"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="12dp"
        android:layout_marginEnd="12dp"
        android:padding="12dp"
        android:textSize="30sp"
        android:inputType="phone"
        android:fontFamily="sans-serif-condensed-medium"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.12" />

</androidx.constraintlayout.widget.ConstraintLayout>
More android kotlin tutorials