0

I want to Validate the list of Email which is comma Separated in Scala.

For Ex:1) [email protected],[email protected],[email protected] ---Valid
       2) [email protected],b@@gmail.com,[email protected]
       3) [email protected],[email protected]@gmail.com----Invalid
Lamanus
  • 12,898
  • 4
  • 21
  • 47
  • Welcome to Stack Overflow! If your question has been correctly answered, consider marking the answer as accepted (like [that](https://i.stack.imgur.com/QpogP.png)) so that it can help future people that come across the same issue :) – leleogere Aug 29 '22 at 08:43

1 Answers1

2

Depending on what "invalid" means, this could work:

def isValid(emails: String): Boolean = {
  return emails.split(",").map(_.count(_ == '@') == 1).reduce(_ && _)
}

isValid("[email protected],[email protected],[email protected]")  // true
isValid("[email protected],b@@gmail.com,[email protected]")  // false
isValid("[email protected],[email protected]@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).

leleogere
  • 908
  • 2
  • 15