Skip to content

Commit

Permalink
Add regex validation to user email
Browse files Browse the repository at this point in the history
Fixes in delayed job to deliver mails:
```
501 Recipient syntax error

/usr/local/lib/ruby/2.5.0/net/smtp.rb:969:in `check_response'
/usr/local/lib/ruby/2.5.0/net/smtp.rb:937:in `getok'
/usr/local/lib/ruby/2.5.0/net/smtp.rb:865:in `rcptto'
/usr/local/lib/ruby/2.5.0/net/smtp.rb:846:in `block in rcptto_list'
```
  • Loading branch information
sonalkr132 committed Jun 7, 2020
1 parent 46420dc commit e791519
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 3 deletions.
2 changes: 1 addition & 1 deletion app/models/user.rb
Expand Up @@ -28,7 +28,7 @@ class User < ApplicationRecord
after_validation :set_unconfirmed_email, if: :email_changed?, on: :update
before_create :generate_api_key, :generate_confirmation_token

validates :email, length: { maximum: 254 }
validates :email, length: { maximum: 254 }, format: { with: URI::MailTo::EMAIL_REGEXP }

validates :handle, uniqueness: true, allow_nil: true
validates :handle, format: {
Expand Down
5 changes: 3 additions & 2 deletions test/unit/helpers/dynamic_errors_helper_test.rb
Expand Up @@ -4,8 +4,9 @@ class DynamicErrorsHelperTest < ActionView::TestCase
test "returns a div with the errors if the object is invalid" do
user = build(:user, email: nil)
user.valid?
expected_dom = %(<div class="errorExplanation" id="errorExplanation"><h2>2 errors prohibited this user from being saved</h2><p>There were \
problems with the following fields:</p><ul><li>Email address is not a valid email</li><li>Email address can't be blank</li></ul></div>)
expected_dom = %(<div class="errorExplanation" id="errorExplanation"><h2>3 errors prohibited this user from being saved</h2><p>There were \
problems with the following fields:</p><ul><li>Email address is not a valid email</li><li>Email address can't be blank</li><li>Email address is \
invalid</li></ul></div>)

assert_dom_equal expected_dom, error_messages_for(user)
end
Expand Down
11 changes: 11 additions & 0 deletions test/unit/user_test.rb
Expand Up @@ -60,6 +60,17 @@ def assert_resetting_email_changes(attr_name)
refute user.valid?
assert_contains user.errors[:email], "is too long (maximum is 254 characters)"
end

should "be valid when it matches URI mail email regex" do
user = build(:user, email: "mail@example.com")
assert user.valid?
end

should "be invalid when it doesn't match URI mail email regex" do
user = build(:user, email: "random[a..z]mdhlwqui@163.com")
refute user.valid?
assert_contains user.errors[:email], "is invalid"
end
end

context "twitter_username" do
Expand Down

0 comments on commit e791519

Please sign in to comment.