How to validate an email in Kotlin in Android

How to validate an email in Kotlin in Android:

In this post, we will learn how to do email validation in Android with Kotlin. We will create one function that will check and validate different types of email addresses.

We have two different ways to do email validation in Kotlin:

  • By using a regular expression or regex
  • By using Android’s utility class.

Method 1: Validate an email with a regular expression:

We can use a regular expression to validate a string. We can use one regex pattern to check if a string is a valid email or not as like below:

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import java.util.regex.Pattern

class MainActivity : AppCompatActivity() {
    val EMAIL_ADDRESS_PATTERN = Pattern.compile(
        "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}\\@[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}(\\.[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25})+"
    )
    fun isValidString(str: String): Boolean{
        return EMAIL_ADDRESS_PATTERN.matcher(str).matches()
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val emails = arrayOf<String>("hello@gmail.com", "one.com", "")

        emails.forEach {
            Log.d("MainActivity", "is valid email $it => ${isValidString(it)}")
        }
    }
}

Download it on GitHub Reference: stack overflow

If you check the logcat, it will print the following logs:

com.codevscolor.myapplication D/MainActivity: is valid email hello@gmail.com => true
com.codevscolor.myapplication D/MainActivity: is valid email one.com => false
com.codevscolor.myapplication D/MainActivity: is valid email  => false

You can use the isValidString function with your UI components to validate any user-input email string.

Method 2: Validate an email using android.util.Patterns class:

The android.util.Patterns class provides different types of matchers to validate patterns. For email addresses, we can use the android.util.Patterns.EMAIL_ADDRESS.matcher() method to validate if an email is valid or not. The following program shows how to use the android.util.Patterns class to validate an email address:

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log

class MainActivity : AppCompatActivity() {

    fun isValidString(str: String): Boolean{
        return android.util.Patterns.EMAIL_ADDRESS.matcher(str).matches()
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val emails = arrayOf("hello@gmail.com", "one.com")

        emails.forEach {
            Log.d("MainActivity","is valid email $it => ${isValidString(it)}")
        }
    }
}

Download it on GitHub

If you check the source of EMAIL_ADDRESS, it is a Pattern variable:

public static final Pattern EMAIL_ADDRESS
        = Pattern.compile(
            "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
            "\\@" +
            "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
            "(" +
                "\\." +
                "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
            ")+"
        );

It will give similar results.

Kotlin example to validate email

Method 3: By using extension function:

We can take the help of extension function functionality of Kotlin to define the validity check in a separate extension function of String:

fun String.isValidEmail() : Boolean = android.util.Patterns.EMAIL_ADDRESS.matcher(this).matches()

This function will be available to all other string variables:

val emails = arrayOf("hello@gmail.com", "one.com", "")

emails.forEach {
    Log.d("MainActivity", "is valid email $it => ${it.isValidEmail()}")
}

It is a better approach as we can avoid duplicate code and we don’t have to call a utility method.

You might also like: