如何仅允许和验证特定URL

时间:2011-06-28 14:17:21

标签: ruby-on-rails

你如何让你的模特text_field只能接受例如Google地图网址:http://maps.google.com/以及.com/后输入的其他内容?以下是我的意思示例:http://maps.google.com/ maps?complete=0&q=Stanford+University,+Menlo+Park,+CA

提前谢谢!

编辑::google_url是我在数据库中的列

validate :google_url_only_accepts_gmaps_url

    def google_url_only_accepts_gmaps_url
        errors.full_messages << "This is not GMaps url!" unless
        google_url =~ /^http:\/\/maps\.google\.com\/maps/
    end

1 个答案:

答案 0 :(得分:2)

为您的字段创建自定义验证:

class MyModel
  validate :text_field_only_accepts_gmaps_url
  def text_field_only_accepts_gmaps_url
    errors.full_messages << "This is not GMaps url!" unless
      text_field =~ /^http:\/\/maps\.google\.com\/maps/
  end
end