How to validate email address in Android with Kotlin?

With the below code we can validate email address in android.

import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
   private lateinit var editText: EditText
   private lateinit var email: String
   private val emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+"
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      editText = findViewById(R.id.editText)
      email = editText.text.toString().trim()
   }
   fun validateEmail(view: View?) {
      if (email.matches(emailPattern.toRegex())) {
         Toast.makeText(applicationContext, "Valid email address",
         Toast.LENGTH_SHORT).show()
      } else {
         Toast.makeText(applicationContext, "Invalid email address",
         Toast.LENGTH_SHORT).show()
      }
   }
}

 


Flutter Questions

Android Questions

Python Questions

Java Questions