This tutorial will show you how to validate email address with regular expression using Kotlin. In web applications or standalone applications where we need to send emails to intended recipients, it is recommended to check the valid email address before sending email to those particular emails for safety purpose. Here we will use regular expression (regex) to validate email address using Kotlin programming language. We will also see how to create Kotlin project in Eclipse.

Please read here how to create Kotlin project in Eclipse.

We will test our program using some sample data to validate email address with regular expression using Kotlin. For each of the test data, the program prints either true or false according to whether valid or invalid email address.

Sample Input

Julia.abc@
Samantha@com
Samantha_21.
.1Samantha
Samantha@10_2A
JuliaZ007
Julia@007.com
_Julia007.com
_Julia007@abc.co.in
Julia.007@abc.com

Sample Output

false
false
false
false
false
false
true
false
false
true

The source code is given below

package com.jeejava.kt

class EmailValidator {
	companion object {
		@JvmStatic val EMAIL_REGEX = "^[A-Za-z](.*)([@]{1})(.{1,})(\.)(.{1,})";
		fun isEmailValid(email: String): Boolean {
			return EMAIL_REGEX.toRegex().matches(email);
		}
	}
}

fun main(args: Array<String>) {
	println(EmailValidator.isEmailValid("Julia.abc@"));
	println(EmailValidator.isEmailValid("Samantha@com"));
	println(EmailValidator.isEmailValid("Samantha_21."));
	println(EmailValidator.isEmailValid(".1Samantha"));
	println(EmailValidator.isEmailValid("Samantha@10_2A"));
	println(EmailValidator.isEmailValid("JuliaZ007"));
	println(EmailValidator.isEmailValid("Julia@007.com"));
	println(EmailValidator.isEmailValid("_Julia007.com"));
	println(EmailValidator.isEmailValid("_Julia007@abc.co.in"));
	println(EmailValidator.isEmailValid("Julia.007@abc.com"));
}

Running the Kotlin program

Do right click on the above Kotlin class and select Run As -> Kotlin Application

Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials Twitter Facebook  Google Plus Linkedin Or Email Me

Leave a Reply

Your email address will not be published. Required fields are marked *