# Improve email validation regex pattern and add comprehensive tests

This commit updates the email validation pattern in Truemail configuration to better handle various email format edge cases. The changes include:
Refine email regex pattern in config/initializers/truemail.rb to properly validate:
RFC compliant local parts with allowed special characters
Proper domain name formatting
Prevention of consecutive dots in both local part and domain
Leading and trailing dots in local part
Add comprehensive test cases in test/interactions/email_check_test.rb to verify:
Valid email formats like standard addresses, underscore usage, and dot-atom formats
Invalid email formats including consecutive dots, leading/trailing dots, and invalid characters
These changes ensure our email validation is more RFC-compliant while still being strict enough to catch common errors. The test suite now explicitly validates both positive and negative test cases for email format validation.
This commit is contained in:
oleghasjanov 2025-03-10 14:24:02 +02:00
parent 1fbfdff1e7
commit f866b549b5
2 changed files with 28 additions and 1 deletions

View file

@ -9,7 +9,7 @@ Truemail.configure do |config|
# config.verifier_domain = 'internet.ee'
# Optional parameter. You can override default regex pattern
config.email_pattern = /(?=\A.{6,255}\z)(\A([\p{L}0-9]+[\W\w]*)@(xn--)?((?i-mx:[\p{L}0-9]+([\-.]{1}[\p{L}0-9]+)*\.\p{L}{2,63}))\z)/
config.email_pattern = /\A([\p{L}0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[\p{L}0-9!#$%&'*+\/=?^_`{|}~-]+)*)@(?i:(xn--)?(?:[\p{L}0-9][\p{L}0-9-]{0,61}[\p{L}0-9]\.)+[\p{L}]{2,63}|\[[\d.a-fA-F:]+\])\z/
# Optional parameter. You can override default regex pattern
# config.smtp_error_body_pattern = /regex_pattern/

View file

@ -7,6 +7,33 @@ class EmailCheckTest < ActiveSupport::TestCase
@contact = contacts(:john)
end
def test_validates_regex_email_format
valid_emails = [
'user@domain.com',
'user_@domain.com',
'user.name@domain.com',
'hello.world@example.com',
'_user.email@domain.com',
'__user.email@domain.com',
]
valid_emails.each_with_index do |email, index|
assert Actions::EmailCheck.new(email: email, validation_eventable: @contact, check_level: 'regex').call
end
invalid_emails = [
'user..name@domain.com',
'.user@domain.com',
'user.@domain.com',
'us"er@domain.com',
'user@domain..com'
]
invalid_emails.each do |email|
refute Actions::EmailCheck.new(email: email, validation_eventable: @contact, check_level: 'regex').call
end
end
def test_invalid_email_in_mx_level_with_a_and_aaaa_records
Spy.on_instance_method(Actions::EmailCheck, :check_email).and_return(trumail_result)
Spy.on_instance_method(Actions::AAndAaaaEmailValidation, :call).and_return([true])