Skip to content

Commit

Permalink
Merge pull request #2389 from sonalkr132/email-regex-validation
Browse files Browse the repository at this point in the history
Add regex validation to user email
  • Loading branch information
sonalkr132 committed Jun 14, 2020
2 parents 0a62a39 + bf64d66 commit bb2ba06
Show file tree
Hide file tree
Showing 3 changed files with 23 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: Gemcutter::MAX_FIELD_LENGTH }, presence: true
validates :email, length: { maximum: Gemcutter::MAX_FIELD_LENGTH }, format: { with: URI::MailTo::EMAIL_REGEXP }, presence: true

validates :handle, uniqueness: true, allow_nil: true
validates :handle, format: {
Expand Down
13 changes: 11 additions & 2 deletions test/unit/helpers/dynamic_errors_helper_test.rb
Expand Up @@ -4,8 +4,17 @@ 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 = <<~HTML.squish.gsub(/>\s+</, "><")
<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>
HTML

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 255 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 bb2ba06

Please sign in to comment.