I want to Validate the list of Email which is comma Separated in Scala.
For Ex:1) a@gmail.com,b@gmail.com,c@gmail.com ---Valid
2) a@gmail.com,b@@gmail.com,c@gmail.com---Invalid
3) a@gmail.com,b@gmail.com.c@gmail.com----Invalid
I want to Validate the list of Email which is comma Separated in Scala.
For Ex:1) a@gmail.com,b@gmail.com,c@gmail.com ---Valid
2) a@gmail.com,b@@gmail.com,c@gmail.com---Invalid
3) a@gmail.com,b@gmail.com.c@gmail.com----Invalid
Depending on what "invalid" means, this could work:
def isValid(emails: String): Boolean = {
return emails.split(",").map(_.count(_ == '@') == 1).reduce(_ && _)
}
isValid("a@gmail.com,b@gmail.com,c@gmail.com") // true
isValid("a@gmail.com,b@@gmail.com,c@gmail.com") // false
isValid("a@gmail.com,b@gmail.com.c@gmail.com") // false
I'm just splitting the string by commas, then I check that there is only one @
in it.
If you really want to check that the email is correct, you can use a regex like this:
def isValid(emails: String): Boolean = {
return emails.split(",").map(_.matches(raw"[\w-\.]+@([\w-]+\.)+[\w-]{2,4}")).reduce(_ && _)
}
This is probably better, but it is not specific enough to capture all email specificities. Matching all types of emails is not something easy to do with regex (see this question).