正则表达式没有在Rails 4应用程序中正确验证

时间:2016-04-23 04:05:06

标签: ruby regex ruby-on-rails-4

我似乎无法通过使用正则表达式传递Rails 4应用程序进行验证。

Subscriber.rb

class Subscriber < ActiveRecord::Base

  validates_uniqueness_of :email, :case_sensitive => false, message: "You're already subscribed!"
  validates_format_of :email, :with => /@/i, message: "Email is invalid"
  before_save { self.email = email.downcase if email}

end

无论我的正则表达式多么简单,我都会得到&#34;电子邮件无效&#34;消息。

任何想法或我做的事情显然是错的(正则表达不适合我)。

谢谢!

_subscribe.html.erb

<%= form_for Subscriber.new do |f| %>
    <%= f.text_field :email, :class => "uppercase", :placeholder => "Stay in touch. Enter your email" %>
    <%= f.submit :class => "submit uppercase", :value => 'submit' %>
<% end %>

调用partial的行: <%= render :partial => 'shared/subscribe', :subscriber => Subscriber.new %>

subscribers_controller.rb

include SubscribersHelper

def create
    @subscriber = Subscriber.new
    if @subscriber.save(subscriber_params)
        redirect_to(:back)
        flash.notice = "You are now subscribed"
    else
        redirect_to(:back)
        flash.alert = "There was an error with your subscription: "
        flash.alert += @subscriber.errors.messages.values.join(", ")
    end
end

SubscribersHelper.rb

def subscriber_params
    params.require(:subscriber).permit(:email)
end

1 个答案:

答案 0 :(得分:0)

 VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, length: { maximum: 255 },
                    format: { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }

上面是一个非常安全的电子邮件RegEx。