rails validation regular expression for www and http

I want to validate a form input so that http:// and www is not allowed. Which REGEX would work?

For example:

Allowed

google.com

NOT Allowed

  • www.google.com
  • http://google.com
  • http://www.google.com

MODEL

VALID_DOMAIN_REGEX = ???

validates :domain, format: { with: VALID_DOMAIN_REGEX }

  • perform one validation only if all other validations pass
  • Collecting first segments of all routes in rails 3
  • Rails 3: Validate IP String
  • How to run validations of sub-class in Single Table Inheritance?
  • Rails: Why “format” (regex) validation fails?
  • After adding controller in active admin resource , validations error cannot be shown
  • Rails 4 radio button form helper, true not validating
  • how can a controller manually set validation errors for a certain field
  • 2 Solutions collect form web for “rails validation regular expression for www and http”

    Since http:// contains so many forward slashes, this would be a good use for Ruby’s %r{} regex literal syntax.

    def has_forbidden_prefix?(string)
      string =~ %r{^(http://|www)}
    end
    

    This will return nil, falsy, if the string does not start with http:// or www.

    It will return 0, truthy (the offset of the first match) if the string does.

    You can use validate :some_method_name to call a custom validation method in the model, I would structure it as follows

    model MyThing
      validate :no_forbidden_prefix
    
      private
    
      def has_forbidden_prefix?(string)
        string =~ %r{^(http://|www)}
      end
    
      def no_forbidden_prefix
        if has_forbidden_prefix?(uri)
          errors.add :domain, 'The URI cannot start with "http://" or "www"'
        end
      end
    end
    

    This should do it for you:

    /^[http\:\/\/|www].*/
    

    For example:

    1.9.2p320 :007 > "http://www.google.de".match /^[http\:\/\/|www].*/
     => #<MatchData "http://www.google.de">
    1.9.2p320 :008 > "www.google.de".match /^[http\:\/\/|www].*/
     => #<MatchData "www.google.de">
    1.9.2p320 :009 > "google.de".match /^[http\:\/\/|www].*/
     => nil
    

    So it doenst match if its valid for your purposes…

    Ruby is the best programming language in the world - Ruby on Rails.