簡體   English   中英

模型外部的Rails驗證

[英]Rails Validation Outside the Model

我需要對我的消息表單進行驗證,在該表單中,該人輸入電子郵件,電子郵件將表單定向到將接收該消息的人的ID。

Email:<br />
    <%= f.text_field :to %>
    <%= error_message_on @message, :to %>
                      ...
            <%= submit_tag "Send" %>

我的問題是,我需要為此表單創建一個驗證以便僅接受電子郵件,但是Message模型本身沒有電子郵件。 最好的嘗試是什么?

創作就是這樣

 def create
@message = Message.new(params[:message])
@message.sender = @profile
@message.recipient = Profile.find_by_email(params[:message][:to])

if @message.save
  flash[:notice] = "Message sent"
  redirect_to profile_messages_path(@profile)
else
  render :action => :new
end
end

提前致謝!

- - 編輯 - -

正如我在上面的評論中所說,我在message.rb中添加了這一行

validates :to, :format   => { :with => email_regex, :message => "Email possui formato incorreto" }

但是經過一些測試,我發現我無法再打開消息了,我收到一條錯誤消息:

Validation failed: To Email possui formato incorreto

有什么線索嗎?

這條線

@message = Message.new(params[:message])

如果消息模型上沒有to =方法,則應該拋出錯誤。 因此,我假設您已經具有這種“虛擬屬性”,所以讓我們這樣說:

def to
  @to
end

def to=(value)
  @to = value
end

要驗證正確的電子郵件地址,可以將其添加到模型中:

validate :validate_email

def validate_email
  errors.add :to, :invalid unless to.match /some email validation regex/
end

我希望這有幫助。

您可以通過javascript進行客戶端檢查,也可以進行自定義驗證: http : //www.perfectline.ee/blog/building-ruby-on-rails-3-custom-validators (您使用的是Rails 3嗎?)

因此,如果我理解正確,您會收到一封電子郵件,只是不想將其存儲在模型中,因為沒有此類字段。

一種方法是使用form_tag而不是form_for來創建自定義表單。 然后,您可以擁有任意數量的非模型屬性。

要檢查那是不是正確的郵件,您將在create操作中接收到參數,並使用一種方法來檢查這是否為有效的電子郵件。 如果不是這樣,它將閃爍一條錯誤消息並重定向到頁面(如果需要)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM