android kotlin - EditText email validation

Android Kotlin - EditText Email Validation

This code demonstrates how to validate email addresses entered in an EditText field within an Android application written in Kotlin. It achieves this by utilizing a TextWatcher and an extension function.

Code Breakdown:

  1. MainActivity.kt:

    • This file defines the MainActivity class which extends the Activity class.
    • It retrieves the reference to the EditText widget with the ID editText from the activity layout.
    • An anonymous TextWatcher is attached to the EditText. This listener monitors text changes within the field.
  2. TextWatcher Implementation:

    • The onTextChanged method of the TextWatcher is overridden. This method is called whenever the text content of the EditText is modified.
    • Inside onTextChanged, the extension function isValidEmail is called on the current text content (p0).
      • If the email is valid (according to the function's logic), the error message on the EditText is cleared (editText.error = null).
      • If the email is invalid, an error message ("Invalid email.") is set on the EditText.
  3. isValidEmail Extension Function:

    • This extension function is defined outside the MainActivity class and operates on a CharSequence? (which can be null or a sequence of characters).
    • It checks two conditions:
      • The text is not null or empty using the isNullOrEmpty method.
      • The text matches the email address pattern using the Patterns.EMAIL_ADDRESS.matcher(this).matches() statement. This leverages the built-in Patterns class from the Android framework.
    • The function returns true if both conditions are met, indicating a valid email address, otherwise it returns false.
  4. activity_main.xml:

    • This file defines the layout for the MainActivity.
    • It uses a ConstraintLayout as the root element.
    • Within the layout, an EditText widget with the ID editText is defined. This EditText is configured to accept email addresses (android:inputType="textEmailAddress").

Summary

This code provides a simple yet effective approach for validating email addresses entered by users in an Android application. The isValidEmail extension function offers a reusable way to check email format, and the TextWatcher ensures real-time feedback to the user as they type. This improves the user experience by guiding them towards entering valid email addresses.


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 text that it is a valid
                // email address or not
                if (p0.isValidEmail()){
                    editText.error = null
                }else{
                    editText.error = "Invalid email."
                }
            }

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

    }
}


// extension function to validate edit text inputted email address
fun CharSequence?.isValidEmail():Boolean{
    return !isNullOrEmpty() && Patterns
        .EMAIL_ADDRESS.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"
    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="textEmailAddress"
        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>
android kotlin - EditText email validation android kotlin - EditText email validation 2
More android kotlin tutorials