Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 友好的表单验证(Rails)_Ruby On Rails_Ruby_Forms_Validation - Fatal编程技术网

Ruby on rails 友好的表单验证(Rails)

Ruby on rails 友好的表单验证(Rails),ruby-on-rails,ruby,forms,validation,Ruby On Rails,Ruby,Forms,Validation,我检查了之前提出的问题,这些问题对我的案例有帮助,但不是一个完整的解决方案 本质上,我需要验证用户从表单提交的URL。我首先验证它是否以http://、https://、或ftp://开头: class Link < ActiveRecord::Base validates_format_of [:link1, :link2, :link3, :link4, :link5], :with => /^(http|https|ftp):\/\/.*/ end cl

我检查了之前提出的问题,这些问题对我的案例有帮助,但不是一个完整的解决方案

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

class Link < ActiveRecord::Base
  validates_format_of [:link1, :link2, :link3, 
        :link4, :link5], :with => /^(http|https|ftp):\/\/.*/
end
class链接/^(http | https | ftp):\/\/*/
结束
这对它所做的工作非常有效,但我需要进一步执行以下两个步骤:

  • 如果需要,应允许用户将表单字段留空,并且
  • 如果用户提供的URL尚未以http://(例如,假设他们进入google.com)开头,则应通过验证,但在处理过程中添加http://前缀

  • 我很难确定如何使这项工作干净高效。

    仅供参考,您不必向
    传递数组来验证
    的格式。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
    
    class链接
    仅供参考,您不必向
    传递数组来验证
    的格式。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
    
    class链接
    为了补充上述内容,我使用Ruby URI模块解析URL的有效性


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

    我使用Ruby URI模块解析URL的有效性

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