Check Ruby on Rails URL (regular expression)

I am trying to use a regular expression to check the format of a URL in my Rails model. I tested the regex in Rubular with the URL http://trentscott.com and it matched.

Any idea why it doesn’t pass the test when I test it in a Rails application (it says "name is incorrect").

The code:

  url_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 => url_regex  }
+5
source share
5 answers

Your entry ( http://trentscott.com ) does not have a subdomain, but the regex validates it.

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

Update

? ((http | https): \/\/), . . . , , ,

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

regexp. Ruby :

# Use the URI module distributed with Ruby:

require 'uri'

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

( :)

+14

( , Addressable)

URL.

Ruby URI Addressable, URL . URI, Addressable tlds.

Usage example:

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/"

And you can create a custom check, for example:

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

Source code

+10
source

Try it. This works for me.
/ (FTP | HTTP | HTTPS): // (\ w + {0,1} \ w * @) (\ S +)? (: [0-9] +) (/ | / ([\ #!:.?!? + = &% @ - /])) /

+1
source

This will include handling the international host as well abc.com.it, where part .itis optional

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
0
source

All Articles