1

Right now, I've got a regular expression that validates a user's facebook link, as such:

facebook_regex = /(http:\/\/)?(https:\/\/)?(www.)?facebook.com\/[a-zA-Z0-9\.]*/i
validates :facebook, :format => { :with => facebook_regex }

The regex itself works just fine, but I'm trying to make the inclusion of a FB link optional, should the user not want theirs posted. However, my validation is kicking up an error if the Facebook field is left blank.

What's the best way to handle this?

Adam Templeton
  • 4,467
  • 7
  • 27
  • 39
  • You didn't ask, but this might be a slightly [better pattern](http://refiddle.com/2nj) (doesn't allow two protocols but an empty path) or you can go [all the way](http://stackoverflow.com/a/190405/95033). :) – Wolfram Jul 17 '12 at 21:41

3 Answers3

4

Try adding allow_blank: true to the validation:

validates :facebook, :format => { :with => facebook_regex }, :allow_blank => true

You could also add in an unless:

validates :facebook, :format => { :with => facebook_regex }, :unless => :blank?
Chris
  • 11,819
  • 19
  • 91
  • 145
0

allow_blank is the option you're looking for:

validates :facebook, format: { with: facebook_regex , allow_blank: true}

stfcodes
  • 1,380
  • 1
  • 9
  • 18
0

Actually, I found the answer right here: http://guides.rubyonrails.org/active_record_validations_callbacks.html

Turns out you can pass an option called :allow_blank that does exactly what I was hoping for!

Adam Templeton
  • 4,467
  • 7
  • 27
  • 39