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.