SixArm.com » Ruby » Email address validation using RFC 822 pattern matching

Author

Joel Parker Henderson, [email protected]

Copyright

Copyright © 2006-2011 Joel Parker Henderson

License

See LICENSE.txt file

Email address regular expression to validate an email address using RFC 822.

This is a gem wrapper around tfletcher.com/lib/rfc822.rb

Example:

if EMAIL_ADDRESS_INNER_PATTERN=~'[email protected]'
  puts "found" 
else
  puts "not found"
end
=> found

Pattern Match

To find an email address in a string, do the pattern match then use the result, which is the match’s string position:

Example of match position:

match_position = EMAIL_ADDRESS_INNER_PATTERN=~'[email protected]'
=> 0

match_position = EMAIL_ADDRESS_INNER_PATTERN=~'... [email protected] ...'
=> 4

match_position = EMAIL_ADDRESS_INNER_PATTERN=~'... hello world ...'
=> nil

Exact Pattern Match

To do an exact pattern match, use the EMAIL_ADDRESS_EXACT_PATTERN. This matches the entire string from start to end; in other words, the entire string must be one email address.

Example of exact pattern match:

if EMAIL_ADDRESS_EXACT_PATTERN=~'[email protected]' 
  puts "found" 
else
  puts "not found"
end
=> found

if EMAIL_ADDRESS_EXACT_PATTERN=~'... [email protected] ...' 
  puts "found" 
else
  puts "not found"
end
=> not found

The exact pattern is especialy useful to validate an email address.

Example to validate an email address:

def valid?(email_address)
  EMAIL_ADDRESS_EXACT_PATTERN=~email_address ? true : false
end

Rails Validation

To add email address validation to a typical Ruby On Rails model:

class User
  include EmailAddressValidation
  validates :email_address, :format => { :with => EMAIL_ADDRESS_EXACT_PATTERN },
end