Sling Academy
Home/Kotlin/Using Regex to Validate Email Addresses in Kotlin

Using Regex to Validate Email Addresses in Kotlin

Last updated: November 30, 2024

Regular expressions, commonly called regex, are a powerful tool for pattern matching and searching text. In this article, we will delve into using regex in Kotlin to validate email addresses. This involves checking that the string follows the general structure of a valid email.

Understanding the Regex Pattern

Email validation generally requires checking that the string contains a username, an at-sign (@), a domain name, and an optional top-level domain. For simplicity, here is a basic regex pattern:

val EMAIL_REGEX = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$"

This regex breaks down as follows:

  • ^[A-Za-z0-9+_.-]+: This matches the username, which can include letters, numbers, and some special characters like '+', '_', '.', and '-'.
  • +: Ensures that there is at least one character present.
  • @: Matches the at-sign that separates the username from the domain.
  • [A-Za-z0-9.-]+: Matches the domain name. It allows letters, numbers, periods (for separating domain parts), and hyphens.
  • $: Ensures the string ends after the domain.

Writing the Validation Function

We will now write a Kotlin function that uses this regex to check if a given email string is valid:

fun isValidEmail(email: String): Boolean {
    val regex = EMAIL_REGEX.toRegex()
    return regex.matches(email)
}

This function converts the string pattern into a Regex object and uses matches() to determine if the entire email string conforms to the regex.

Testing the Validation Function

We can now test our function with various email addresses:


fun main() {
    val validEmails = listOf(
        "[email protected]",
        "user+mailbox/[email protected]",
        "[email protected]",
        "simple@localhost"
    )

    val invalidEmails = listOf(
        "plainaddress",
        "@missingusername.com",
        "[email protected]",
        "[email protected]"
    )

    println("Valid Emails")
    for (email in validEmails) {
        println("Is '")
        println(" '$email' valid? ${isValidEmail(email)}")
    }

    println("\nInvalid Emails")
    for (email in invalidEmails) {
        println("Is $email valid? ${isValidEmail(email)}")
    }
}

This simple test verifies that the provided emails yield expected results.

Conclusion

Regex provides a succinct way to encapsulate complex search patterns like email addresses. Using Kotlin, you can easily implement this for various purposes including input validation. However, always remember that regex for email validation may not cover all cases, especially for production-level applications, as email formats can vary widely according to different standards.

Next Article: Phone Number Validation with Regular Expressions in Kotlin

Previous Article: Matching Strings with Regular Expressions in Kotlin

Series: Primitive data types in Kotlin

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin