Skip to content
lyang edited this page Mar 19, 2013 · 4 revisions

Validations

BraintreeRails models implement most, if not all, the ActiveModel interfaces, including ActiveModel::Validations.

Model validations

BraintreeRails models all has default validations, except readonly models like Plan. For example, BraintreeRails::Address has the following validations:

module BraintreeRails
  class AddressValidator < Validator
    Validations = [
      [:first_name, :last_name, :company, :street_address, :extended_address, :locality, :region, :length => {:maximum => 255}],
      [:country_code_numeric, :allow_blank => true, :inclusion => { :in => Braintree::Address::CountryNames.map {|country| country[3]} }],
      [:street_address, :presence => true, :if => Proc.new { Configuration.require_street_address }],
      [:postal_code, :presence => true, :format => { :with => /\A[- a-z0-9]+\z/i}, :if => Proc.new { Configuration.require_postal_code }]
    ]
  end
end

The reason validations are written in an Array constant is to allow customization of the validations. But you get the idea. Behind the scenes it uses the same set of validators as ActiveRecord.

Validation Errors

Validations are run the same way as ActiveRecord, valid?, save, create!, etc. When validations fail, errors will be populated the same way as ActiveRecord. For example,

address = BraintreeRails::Address.new(:first_name => 'long text' * 255)
address.valid? # => false
address.errors.full_messages # => ["First name is too long"]

In addition, when there are api validation errors, for example, invalid credit card cvv value, the errors will be extracted out from the api response and populated into the model objects. For example:

credit_card = customer.credit_cards.create(:number => "encryped_by_braintree_js", :cvv => "fat_fingered")
credit_card.persisted? # => false
credit_card.errors[:cvv].first # => Something like "Cvv does not match"
credit_card.errors[:cvv].first.code # => Error code returned from api response

With the ActiveModel compatible interfaces, the rails form helpers will render those errors inline the same way as ActiveRecord.

Clone this wiki locally