Ruby Email validation with regex

前端 未结 9 872
有刺的猬
有刺的猬 2020-12-03 00:21

I have a large list of emails I am running through. A lot of the emails have typos. I am trying to build a string that will check valid emails.

this is what I have

相关标签:
9条回答
  • 2020-12-03 01:11

    This one is more short and safe:

    /\A[^@\s]+@[^@\s]+\z/
    

    The regular is used in Devise gem. But it has some vulnerabilities for these values:

      ".....@a....",
      "david.gilbertson@SOME+THING-ODD!!.com",
      "a.b@example,com",
      "a.b@example,co.de"
    

    I prefer to use regexp from the ruby library URI::MailTo::EMAIL_REGEXP

    There is a gem for email validations

    Email Validator

    0 讨论(0)
  • 2020-12-03 01:11

    Nowadays Ruby provides an email validation regexp in its standard library. You can find it in the URI::MailTo module, it's URI::MailTo::EMAIL_REGEXP. In Ruby 2.4.1 it evaluates to

    /\A[a-zA-Z0-9.!\#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*\z/
    

    But I'd just use the constant itself.

    0 讨论(0)
  • 2020-12-03 01:14

    TL;DR:

    credit goes to @joshuahunter (below, upvote his answer). Included here so that people see it.

    URI::MailTo::EMAIL_REGEXP
    

    Old TL;DR

    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
    

    Original answer

    You seem to be complicating things a lot, I would simply use:

    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
    

    which is taken from michael hartl's rails book

    since this doesn't meet your dot requirement it can simply be ammended like so:

    VALID_EMAIL_REGEX = /\A([\w+\-]\.?)+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
    

    As mentioned by CAustin, there are many other solutions.

    EDIT:

    it was pointed out by @installero that the original fails for subdomains with hyphens in them, this version will work (not sure why the character class was missing digits and hyphens in the first place).

    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
    
    0 讨论(0)
提交回复
热议问题