Sling Academy
Home/Kotlin/Phone Number Validation with Regular Expressions in Kotlin

Phone Number Validation with Regular Expressions in Kotlin

Last updated: November 30, 2024

Validating phone numbers is a common task in many applications, especially those that require reliable user contact information. In this article, we'll explore how to perform phone number validation using regular expressions in Kotlin.

Understanding Regular Expressions

Regular expressions (regex) are sequences of characters that define a search pattern. Although complex, they are powerful tools for pattern matching and string searching. In this context, we'll create a regex pattern for matching valid phone numbers.

Phone Number Pattern

A phone number can have multiple formats. For illustration, let's assume our application will accept numbers formatted in one of the following ways:

  • 123-456-7890
  • (123) 456-7890
  • 123 456 7890
  • 123.456.7890
  • +31636363634
  • 075-63546725

Review the formats to form a general pattern, which might include delimiters like spaces, hyphens, or dots and optionally a country code.

Writing the Regex for Phone Numbers

The following is a sample regular expression pattern in Kotlin to match the described phone number formats:


val phoneRegex = """^((\+\d{1,2}\s?)?(\(\d{1,3}\)|\d{1,3})[\s.-]?\d{3}[\s.-]?\d{4})$""".toRegex()

Explanation:

  • \+\d{1,2}\s? – Matches an optional country code preceded by a plus sign, followed by a space.
  • \(\d{1,3}\)|\d{1,3} – Matches area code within parentheses or as three consecutive digits.
  • [\s.-]? – Matches optional space, dot, or hyphen.
  • \d{3} – Matches exactly three digits.
  • [\s.-]? – Again for optional space, dot, or hyphen.
  • \d{4} – Matches exactly four digits at the end.

Validating the Phone Number

Once the regular expression is defined, you can easily validate input phone numbers in Kotlin with it. Here's how you can use the regex pattern to validate phone numbers:


fun isValidPhoneNumber(number: String): Boolean {
    return phoneRegex.matches(number)
}

fun main() {
    val phoneNumbers = listOf(
        "123-456-7890",
        "(123) 456-7890",
        "123 456 7890",
        "123.456.7890",
        "+31636363634",
        "075-63546725",
        "wrong number"
    )

    for (number in phoneNumbers) {
        println("$number: ${isValidPhoneNumber(number)}")
    }
}

The isValidPhoneNumber function will return true for inputs matching the pattern, and false otherwise. Running the main function will print the validation result for each phone number in the list.

Conclusion

By utilizing regular expressions, validating phone numbers in Kotlin can be efficient and concise. Customize your regex pattern according to your application's needs and the specific phone number formats you aim to support. Regular expressions provide the adaptability to enforce a wide variety of custom formatting rules with minimal code overhead.

Next Article: How to Check for Alphanumeric Strings with Regex in Kotlin

Previous Article: Using Regex to Validate Email Addresses 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