0

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

MODEL

VALID_DOMAIN_REGEX = ???

validates :domain, format: { with: VALID_DOMAIN_REGEX }

2 Answers 2

0

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
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks, I edited my question. How can I include your solution in my model?
I have expanded my solution to give an example implementation, I find custom validations using private methods much more readable but this is just my opinion. :)
undefined local variable or method `uri'
I wasn't meaning that you should copy it verbatim ;) You want to supply the domain field that you are validating here.
Sorry, I'm a bit confused. So how can I finally validate the :domain column? Something like validates :domain, :no_forbidden_prefix? Or in the controller?
|
0

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...

3 Comments

[http\:\/\/|www] is a character class, maybe you intended to use grouping?
Thanks, but it doesn't work when I do something like that: "www.google.com".sub(/^[http\:\/\/|www]./, "") => "w.google.com"
@toro2k yes I need to use grouping

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.