Skip to content

Instantly share code, notes, and snippets.

@ironic-name
Last active September 23, 2022 18:03
Show Gist options
  • Star 28 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save ironic-name/f8e8479c76e80d470cacd91001e7b45b to your computer and use it in GitHub Desktop.
Save ironic-name/f8e8479c76e80d470cacd91001e7b45b to your computer and use it in GitHub Desktop.
Kotlin regex email validator function
fun isEmailValid(email: String): Boolean {
return Pattern.compile(
"^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]|[\\w-]{2,}))@"
+ "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+ "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
+ "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+ "[0-9]{1,2}|25[0-5]|2[0-4][0-9]))|"
+ "([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$"
).matcher(email).matches()
}
@sandboiii
Copy link

sandboiii commented Dec 30, 2018

There is an easier solution for Android:

fun isEmailValid(email: String): Boolean { 
    return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()
}

@Payne-X6
Copy link

Payne-X6 commented Jan 1, 2019

from android.util.Patterns

private val emailRegex = compile(
        "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
                "\\@" +
                "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
                "(" +
                "\\." +
                "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
                ")+"
)

use:

emailRegex.matcher("john.doe@mail.com").matches()

or

fun String.isEmail() : Boolean {
    return emailRegex.matcher(this).matches()
}
"john.doe@mail.com".isEmail()

@amolpednekar
Copy link

The pattern in the gist does not allow emails of type abc+3@example.com

@brunoluan7
Copy link

brunoluan7 commented Sep 23, 2022

There is an easier solution for Android:

fun isEmailValid(email: String): Boolean { 
    return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()
}

Thanks alot, @sandboiii 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment