2009-01-25 59 views
0

我檢出了boththese之前問過的問題,它們對我的情況有幫助但不是完整的解決方案。友好表單驗證(Rails)

本質上,我需要從窗體驗證用戶提交的URL。 // HTTPS://或ftp://:我已經通過驗證,它以http開始啓動

class Link < ActiveRecord::Base 
    validates_format_of [:link1, :link2, :link3, 
     :link4, :link5], :with => /^(http|https|ftp):\/\/.*/ 
end 

這能很好的完成它在做什麼,但我需要進一步去這兩個步驟:

  1. 應該允許用戶如果需要離開表單字段爲空,
  2. 如果由用戶提供的網址沒有以http://(說他們輸入google.com,例如),它應該通過驗證,但在處理時添加http://前綴。

我很難確定如何使這項工作乾淨有效。

回答

3

僅供參考,您不必將數組傳遞到validates_format_of。 Ruby將自動執行數組(Rails分析*args的輸出)。

因此,對於你的問題,我會去這樣的事情:

class Link < ActiveRecord::Base 
    validate :proper_link_format 

    private 

    def proper_link_format 
    [:link1, :link2, :link3, :link4, :link5].each do |attribute| 
     case self[attribute] 
     when nil, "", /^(http|https|ftp):\/\// 
     # Allow nil/blank. If it starts with http/https/ftp, pass it through also. 
     break 
     else 
     # Append http 
     self[attribute] = "http://#{self[attribute]}" 
     end 
    end 
    end 
end