Last active
September 30, 2024 09:12
-
-
Save ironic-name/f8e8479c76e80d470cacd91001e7b45b to your computer and use it in GitHub Desktop.
Kotlin regex email validator function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} |
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("[email protected]").matches()
or
fun String.isEmail() : Boolean {
return emailRegex.matcher(this).matches()
}
"[email protected]".isEmail()
The pattern in the gist does not allow emails of type [email protected]
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
There is an easier solution for Android: