我似乎無法通過使用正則表達式在電子郵件中傳遞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
不管我正則表達式是多麼的簡單,我得到的「電子郵件無效」的字樣。
任何想法或我做的事情顯然是錯誤的(正則表達式對我來說不是一個強項)。
謝謝!
_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 %>
調用部分線路: <%= 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
如果你正在包含任何包含'@'的東西,它將被顯示爲無效,因爲你的正則表達式是這樣的..在沒有'@'的字符串上試試 – rock321987
我試着用'/.*替換正則表達式@。* /' - 'validates'可能期望正則表達式匹配整個字符串。 – javanut13
@ rock321987 - 嘗試使用不包含@的字符串不起作用 –