0

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
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("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).

leleogere
  • 908
  • 2
  • 15