-
Notifications
You must be signed in to change notification settings - Fork 22
Advanced
BraintreeRails provided a set of default validations. Those default validations should cover the majority of the use cases.
However, if you do have special needs, its quite easy to customize the validations to your needs.
All builtin validations are listed in each models validator classes. For example, BraintreeRails::Address
validations are in an array in the constant BraintreeRails::AddressValidator::Validations
BraintreeRails::AddressValidator::Validations
# [
# [:customer_id, :presence => true, :length => {:maximum => 36}, :on => :create],
# [: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 }]
# ]
Each of the validation in the list will be added to its model class.
In order to add additional validations, you need to first add your validations to that list and re-setup the validations.
For example, if you only take US & Canada credit card, you can do
# Adding validations
BraintreeRails::AddressValidator::Validations << [:country_code_numeric, :inclusion => {:in => ['124', '840']}]
# Re-setup
BraintreeRails::AddressValidator.setup
Similarly to add validations, you can remove validations that doesn't fit your needs. For example:
# Removing the last validation
BraintreeRails::AddressValidator::Validations.pop
# Re-setup
BraintreeRails::AddressValidator.setup
You can change default validations by removing the default one then add a new one and re-setup
If you have complex validation logic, you have two options:
- Extract the logic into a validator and add it to the validation lists. You can take the
BraintreeRails::Luhn10Validator
used inBraintreeRails::CreditCardValidator
for example.
[:number, :numericality => { :only_integer => true }, :length => {:minimum => 12, :maximum => 19}, 'braintree_rails/luhn_10' => true, :if => Proc.new { Configuration.mode == Configuration::Mode::S2S }]
2. Open the model class and add your custom validation method
ruby
module BraintreeRails
class CreditCard
validate :some_complex_validation_logic
def some_complex_validation_logic
end
end
end
```
BraintreeRails has almost the same set of callbacks with ActiveRecord
.
For example, you can persist each successful transaction creation by open the class
module BraintreeRails
class Transaction
after_create :save_in_db_for_analysis
def save_in_db_for_analysis
save_to_my_db(self.as_json)
end
end
end
Or simply just the following
BraintreeRails::Transaction.after_create do
save_to_my_db(self.as_json)
end