(我喜歡托馬斯Hupkens的回答,但對於其他人觀看,我給你推薦尋址)
不建議使用正則表達式來驗證URL。
使用Ruby的URI庫或諸如Addressable之類的替代品,這兩者都使URL驗證變得微不足道。與URI不同,Addressable還可以處理國際字符和tld。
實例應用:
require 'addressable/uri'
Addressable::URI.parse("кц.рф") # Works
uri = Addressable::URI.parse("http://example.com/path/to/resource/")
uri.scheme
#=> "http"
uri.host
#=> "example.com"
uri.path
#=> "/path/to/resource/"
而且你可以建立一個自定義的驗證,如:
class Example
include ActiveModel::Validations
##
# Validates a URL
#
# If the URI library can parse the value, and the scheme is valid
# then we assume the url is valid
#
class UrlValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
begin
uri = Addressable::URI.parse(value)
if !["http","https","ftp"].include?(uri.scheme)
raise Addressable::URI::InvalidURIError
end
rescue Addressable::URI::InvalidURIError
record.errors[attribute] << "Invalid URL"
end
end
end
validates :field, :url => true
end
Code Source
感謝?這解決了錯誤,但現在像「abcd」這樣的條目是有效的。任何想法如何解決這個問題? – 2011-06-03 19:06:12
更新應該有效。還有一件事我刪除了[ - 。],並用\替換。 – cordsen 2011-06-03 19:49:36
謝謝,感謝您的幫助! :) – 2011-06-04 18:52:55