【问题标题】:Friendly Form Validations (Rails)友好的表单验证(Rails)
【发布时间】:2009-01-25 17:47:06
【问题描述】:

我查看了both 中的these 以前提出的问题,它们对我的情况有帮助,但不是完整的解决方案。

基本上我需要从表单验证用户提交的 URL。我首先验证它是否以 http://、https:// 或 ftp:// 开头:

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

这很适合它正在做的事情,但我需要更进一步:

  1. 如果需要,应允许用户将表单字段留空,并且
  2. 如果用户提供的 URL 不是以 http:// 开头(例如他们输入 google.com),它应该通过验证,但在处理时添加 http:// 前缀。李>

我很难确定如何干净高效地完成这项工作。

【问题讨论】:

    标签: ruby-on-rails ruby forms validation


    【解决方案1】:

    仅供参考,您不必将数组传递给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
    

    【讨论】:

      【解决方案2】:

      补充一下,我使用 Ruby URI 模块来解析 URL 的有效性。

      http://www.ruby-doc.org/stdlib/libdoc/uri/rdoc/classes/URI.html

      它工作得非常好,它可以帮助我避免正则表达式。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-26
        • 2013-05-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多