LearningRoR
LearningRoR

Reputation: 27222

How to allow and validate a specific URL only

How do you have your Model's text_field only be able to accept for example, the Google Maps URL: http://maps.google.com/ along with anything else typed after .com/? Here is an example of what i mean: http://maps.google.com/maps?complete=0&q=Stanford+University,+Menlo+Park,+CA.

Thank you in advance!

EDIT: :google_url is my column in database

validate :google_url_only_accepts_gmaps_url

    def google_url_only_accepts_gmaps_url
        errors.full_messages << "This is not GMaps url!" unless
        google_url =~ /^http:\/\/maps\.google\.com\/maps/
    end

Upvotes: 0

Views: 168

Answers (1)

keymone
keymone

Reputation: 8104

create a custom validation for your field:

class MyModel
  validate :text_field_only_accepts_gmaps_url
  def text_field_only_accepts_gmaps_url
    errors.full_messages << "This is not GMaps url!" unless
      text_field =~ /^http:\/\/maps\.google\.com\/maps/
  end
end

Upvotes: 2

Related Questions