2011-06-03 52 views
5

我正嘗試使用正則表達式來驗證我的Rails模型中域名的格式。我已經使用域名http://trentscott.com測試了Rubular中的正則表達式,並與之匹配。Ruby on Rails域名驗證(正則表達式)

任何想法爲什麼它沒有通過驗證,當我在我的Rails應用程序中測試它(它說「名稱無效」)。

代碼:

domain_regex = /^((http|https):\/\/)?[a-z0-9]+([-.]{1}[a-z0-9]+).[a-z]{2,5}(:[0-9]{1,5})?(\/.)?$/ix 

    validates :serial, :presence => true 
    validates :name, :presence => true, 
        :format => { :with => domain_regex } 

回答

6

你輸入(http://trentscott.com)沒有一個子域,但正則表達式的檢查之一。

domain_regex = /^((http|https):\/\/)[a-z0-9]*(\.?[a-z0-9]+)\.[a-z]{2,5}(:[0-9]{1,5})?(\/.)?$/ix 

更新

你也不需要? ((http | https):\/\ /之後),除非該協議有時會丟失。我也逃脫了。因爲那會匹配任何角色。我不知道上面的分組是爲了,但這裏是由部分

domain_regex = /^((http|https):\/\/) 
(([a-z0-9-\.]*)\.)?     
([a-z0-9-]+)\.       
([a-z]{2,5}) 
(:[0-9]{1,5})? 
(\/)?$/ix 
+0

感謝?這解決了錯誤,但現在像「abcd」這樣的條目是有效的。任何想法如何解決這個問題? – 2011-06-03 19:06:12

+1

更新應該有效。還有一件事我刪除了[ - 。],並用\替換。 – cordsen 2011-06-03 19:49:36

+0

謝謝,感謝您的幫助! :) – 2011-06-04 18:52:55

14

你並不需要在這裏使用正則表達式支持破折號和羣體一個更好的版本。 Ruby有一個更可靠的方式來做到這一點:

# Use the URI module distributed with Ruby: 

require 'uri' 

unless (url =~ URI::regexp).nil? 
    # Correct URL 
end 

(這個回答來自this post :)

+2

這不適用於:「http:// nytimes」(IGNORE SPACE) – 2013-08-01 02:38:41

9

(我喜歡托馬斯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

+1

在尋找可尋址的地址後,我認爲它贏得了雙手,感謝 – stephenmurdoch 2011-08-20 20:29:54

+0

+1可尋址但是不要認爲它會引發任何異常,因爲它不會。 Addressable :: URI.parse將無法默默地嘗試找出URI。例如,假設你想驗證一個不正確的URI,比如:http:// http://thing.com。 Addressable將會調用方案http和域http,因爲它將冒號視爲端口分隔符。不會出現錯誤 – onetwopunch 2017-03-15 21:09:00

1

試試這個。 它爲我工作。 (\ S +)(:[0-9] +)?(/ | /([\ w})(\ s +)(:[0- 9] !#:?!+ = &%@ - /))/

0

這將包括國際主機處理以及像abc.com.it其中.it部分是可選

match '/:site', to: 'controller#action' , constraints: { site: /[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}(.[a-zA-Z]{2,63})?/}, via: :get, :format => false