teresa
teresa

Reputation: 366

Rails how to validate optional form field?

I have an optional form field :meetup_apikey and a custom validation method api_key_valid? to check if the API request returned is successful. But I only want to check for validation if the meetup_apikey form field is not empty (user entered something on form submit). If the meetup_apikey form field is empty, I want to ignore the validation and allow the form to save.

Looked at: http://guides.rubyonrails.org/v2.3.11/activerecord_validations_callbacks.html documentation and Validation to ensure uniqueness of but ignoring empty values?.

This is what I have in my model:

validates :meetup_apikey, allow_blank: true
validates :api_key_valid?, :if => :meetup_apikey

def api_key_valid?
    url = "https://api.meetup.com/2/events?key=#{meetup_apikey}&sign=true&photo-host=public&group_urlname=#{meetup_urlname}"
    if !HTTParty.get(url).success?
    errors.add(:meetup_apikey, "Meetup API key must be valid")
    end
end

But this still forces the check, even if nothing is entered in the :meetup_apikey form field. I'm not sure what I am missing or writing wrong.

Any suggestions would help. Thanks!

Upvotes: 2

Views: 1615

Answers (1)

Andrey Deineko
Andrey Deineko

Reputation: 52347

Here is how you'd apply api_key_valid? validation only if meetup_apikey attribute is non-blank:

validates :api_key_valid?, unless: ->(x) { x.meetup_apikey.blank? }

Upvotes: 4

Related Questions