开发者

Dynamic Model Validation

I want to create some validations for one of my models which contain location information(street, locality, postal_code, etc). I want to be able to change the validation rules based on which country is selected.

For example, the validation rules for postal_code will be different for the US & Canada. Furthermore, some countries don't have开发者_如何学编程 postal_codes so no validation rules would be needed.

How would I go about implementing something like this?


Put this in your model to run any custom logic for validation.

validate :location_should_be_valid

def location_should_be_valid

  # run all your custom logic here

  # if it isn't valid, add an error indicating why
  if country == "Canada"
    errors.add(:postal_code, "Invalid postal code for Canada") if postal_code.length != 7
  end
end

Read more about this in the Rails Guides:
http://guides.rubyonrails.org/active_record_validations_callbacks.html#creating-custom-validation-methods


validates :postal_code, :presence => true, :if => :check_country

def check_country
  ["US", "Canada"].include?(self.country)
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜