0

I have a two validation in my model abc.rb

validates_format_of :url, :with => URI::regexp(%w(http https))
validates_format_of :targetUrl, :with => URI::regexp(%w(http https))

validates_format_of :targetUrl 

is not validating the input. whatever I input it accepts. Same issue I am having on other model where I have a validation validates_format_of :website, :with => URI::regexp(%w(http https)). I am not able to figure out why validation failing for
validates_format_of :targetUrl, :with => URI::regexp(%w(http https)) and validates_format_of :website, :with => URI::regexp(%w(http https)).

Any hints will be very helpful. Thanks

user588324
  • 310
  • 1
  • 6
  • 19

1 Answers1

0

You don't need to specify the regex formatting that way. Use something like:

validates :website, format: { with: /(http|https):\/\/[a-zA-Z0-9\-\#\/\_]+[\.][a-zA-Z0-9\-\.\#\/\_]+/i }

And obviously use whatever regex you like!

Tyler
  • 11,272
  • 9
  • 65
  • 105
  • Same issue. I am curious why same validation not working on other fields. – user588324 Sep 26 '13 at 16:44
  • Same issue as what? This is the validation I use in one of my applications, so it definitely works... – Tyler Sep 26 '13 at 16:50
  • its not validating the url. I type garbage it accepts. Plus I am not looking for new validation. I am want to know why same validation format works for one field and not working for other. – user588324 Sep 26 '13 at 17:02
  • Make sure you are calling all the validations for a given field in the same place. In your case, calling `validates_format_of` more than once will simply override the others. – Tyler Sep 26 '13 at 17:14
  • I already tried that and that didnt help. In one of the model this validation 'validates_format_of :website, :with => URI::regexp(%w(http https))' doesn't work at all. – user588324 Sep 26 '13 at 17:25
  • I suggested that you not use that format; use the format I posted for all of your validations instead. You can chain onto each, e.g. `validates :website, length: { maximum: 50 }, format: { with: /(http|https):\/\/[a-zA-Z0-9\-\#\/\_]+[\.][a-zA-Z0-9\-\.\#\/\_]+/i, message: "must be http:// or https:// and without additional characters (?, %, =, etc)" }, allow_blank: true` – Tyler Sep 26 '13 at 17:28