Validation for URL/Domain using Regex? (Rails)

后端 未结 13 1760
野的像风
野的像风 2020-11-29 21:10

I am trying to create a validation that checks to make sure a domain/url is valid for example \"test.com\"

def valid_domain_name?
  domain_name = domain.spli         


        
相关标签:
13条回答
  • 2020-11-29 21:33

    Better answer since Ruby 1.8.6

    require 'uri'
    
    def valid_url?(url)
      url.slice(URI::regexp(%w(http https))) == url
    end
    
    0 讨论(0)
  • 2020-11-29 21:36

    @Tate's answer is good for a full URL, but if you want to validate a domain column, you don't want to allow the extra URL bits his regex allows (e.g. you definitely don't want to allow a URL with a path to a file).

    So I removed the protocol, port, file path, and query string parts of the regex, resulting in this:

    ^[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}$


    Check out the same test cases for both versions.

    • Original (allows domains or full URLs): http://rubular.com/r/qGInC06jcz
    • Modified (allows only domains): http://rubular.com/r/yP6dHFEhrl
    0 讨论(0)
  • 2020-11-29 21:39

    Another way to do URL validation in Rails is

    validates :web_address, :format => { :with => URI::regexp(%w(http https)), :message => "Valid URL required"}
    
    0 讨论(0)
  • 2020-11-29 21:40

    Stumbled on this:

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

    FYI: Rubular is a fantastic resource for testing your Ruby regular expressions

    0 讨论(0)
  • 2020-11-29 21:48
    ^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$
    

    Domain name validation with RegEx

    0 讨论(0)
  • 2020-11-29 21:50

    I took what you had and modified it so that I could make the http:// or https:// optional:

    /^((http|https):\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/ix
    
    0 讨论(0)
提交回复
热议问题