18 - validating an email address.rb

来自「O Reilly Ruby Cookbook source code」· RB 代码 · 共 65 行

RB
65
字号
test_addresses = [ #The following are valid addresses according to RFC822.                   'joe@example.com', 'joe.bloggs@mail.example.com',                   'joe+ruby-mail@example.com', 'joe(and-mary)@example.museum',                   'joe@localhost', #---                   'joe', 'joe@', '@example.com',                   'joe@example@example.com',                   'joe and mary@example.com' ]#---valid = '[^ @]+' # Exclude characters always invalid in email addressesusername_and_machine = /^#{valid}@#{valid}$/test_addresses.collect { |i| i =~ username_and_machine }# => [0, 0, 0, 0, 0, nil, nil, nil, nil, nil]#---username_and_machine_with_tld = /^#{valid}@#{valid}\.#{valid}$/test_addresses.collect { |i| i =~ username_and_machine_with_tld }# => [0, 0, 0, 0, nil, nil, nil, nil, nil, nil]#---def probably_valid?(email) valid = '[A-Za-z\d.+-]+' #Commonly encountered email address characters (email =~ /#{valid}@#{valid}\.#{valid}/) == 0end#These give the correct result.probably_valid? 'joe@example.com'                # => trueprobably_valid? 'joe+ruby-mail@example.com'      # => trueprobably_valid? 'joe.bloggs@mail.example.com'    # => trueprobably_valid? 'joe@examplecom'                 # => falseprobably_valid? 'joe+ruby-mail@example.com'      # => trueprobably_valid? 'joe@localhost'                  # => false# This address is valid, but probably_valid thinks it's not.probably_valid? 'joe(and-mary)@example.museum'   # => false# This address is valid, but certainly wrong.probably_valid? 'joe@example.cpm'                # => true#---require 'resolv'def valid_email_host?(email)  hostname = email[(email =~ /@/)+1..email.length]  valid = true  begin    Resolv::DNS.new.getresource(hostname, Resolv::DNS::Resource::IN::MX)  rescue Resolv::ResolvError    valid = false  end  return validend#example.com is a real domain, but it won't accept mailvalid_email_host?('joe@example.com')          # => false#lcqkxjvoem.mil is not a real domain.valid_email_host?('joe@lcqkxjvoem.mil')       # => false#oreilly.com exists and accepts mail, though there might not be a 'joe' there.valid_email_host?('joe@oreilly.com')          # => true#---

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?