0

I want validate many mails ( one or more) with regex expression but this attribute don´t belongs to any model. So I wrote a method:

def emails_are_valid?(emails)
     #regex with validation  
     regex = Regexp.new("^(\s*[a-zA-Z0-9\._%-]+@[a-zA-Z0-9\.-]+\.[a-zA-Z]{2,4}\s*([,]{1}[\s]*[a-zA-Z0-9\._%-]+@[a-zA-Z0-9\.-]+\.[a-zA-Z]{2,4}\s*)*)$")
     #if the quantity of emails is zero o its validations is bad return false.   
     if emails.blank? || emails.match(regex).nil?
          return false
        else
          return true
        end
end

I evaluate this string mm@somedomain.com aa, mma@somedomain.com when I tested this regex in http://www.rubular.com/ is bad (no matches). So According to this page my regex is ok.

But when I evaluate emails.match(regex).nil? that returns me false (So the string is valid, but this string is bad)

Please I need help. my regex is bad or my emails_are_valid? method is bad or match method is bad.

Thanks in advance.

maxiperez
  • 1,470
  • 2
  • 20
  • 40
  • 1
    It would be good for you to read [Regexp recognition of email address hard?](http://stackoverflow.com/q/156430/128421) and see if you really want to bother with trying to validate an email address using a regex, or just find out if the email will actually deliver to an address. The difference is having an address that looks good, or having an address you know is good. [Search StackOverflow](http://stackoverflow.com/search?q=%2Bregex+%2Bemail) for similar questions. – the Tin Man Feb 17 '11 at 18:03
  • @the Tin Man I want validate format and I want to validate the format of the mail and that the comma-separated list regardless of the amount of space between them and the comma. However when I place a space + lyrics + coma + other_mail the match method returns as if it were correct – maxiperez Feb 17 '11 at 18:07

1 Answers1

1

You should have used single quotes instead of double quotes when declaring your regex, otherwise \s gets parsed as an escape sequence.

Change that line to

 regex = Regexp.new('^(\s*[a-zA-Z0-9\._%-]+@[a-zA-Z0-9\.-]+\.[a-zA-Z]{2,4}\s*([,]{1}[\s]*[a-zA-Z0-9\._%-]+@[a-zA-Z0-9\.-]+\.[a-zA-Z]{2,4}\s*)*)$')

and the method will work.

On a side note, this would be a more concise way of doing the same thing - http://codepad.org/YbsqIkcP

Dogbert
  • 212,659
  • 41
  • 396
  • 397