Adam Templeton
Adam Templeton

Reputation: 4617

Rails: Only using regex when data is present

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?

Upvotes: 1

Views: 166

Answers (3)

Adam Templeton
Adam Templeton

Reputation: 4617

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!

Upvotes: 0

stfcodes
stfcodes

Reputation: 1380

allow_blank is the option you're looking for:

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

Upvotes: 0

Chris
Chris

Reputation: 12181

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?

Upvotes: 4

Related Questions