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 using Kotlin. We will create one function that will check and validate different types of email addresses.

We have two different ways to do a email validation : By using a regular expressionn or regex and by using Android’s utility class.

Example using regular expression :

We can use a regular expression to validate a string. We can use one regex pattern to check if a string is 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)}")
        }
    }
}

Reference : stack overflow

If you check the logcat, it will print something like below:

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

Example using android.util.Patterns :

android.util.Patterns provides different types of pattern matchers. For email adress also, we can do matching just right out of the box. Below is the complete program that uses android.util.Patterns :

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<String>("hello@gmail.com", "one.com")

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

We can also configure these functions as extension function.

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us 😊