DEV Community

Discussion on: I hated Regex so much that I made iHateRegex.io

 
jmfayard profile image
Jean-Michel πŸ•΅πŸ»β€β™‚οΈ Fayard • Edited

To pre-validate, you can keep it simple like this:

fun main() {
    val emails = listOf("john@example.com", "John Doe")
    emails.forEach { println("input=$it isEmail=${it.isEmail()}")}
    // input=john@example.com isEmail=true
    // input=John Doe isEmail=false

    val phones = listOf(" 5555555555 ", "+1 (555) 555-5555", "555 - 555 - 5555", "invalid")
    phones.forEach { println(it.normalizePhoneNumber()) }
    // 5555555555
    // 15555555555
    // 5555555555
    // null
}

fun String.isEmail(): Boolean = 
    length > 6 && contains("@")

fun String.normalizePhoneNumber(): String? =
    this.filter { it.isDigit() }.takeIf { it.length > 6 }