Class: Gemgento::CreditCardValidator
- Inherits:
-
ActiveModel::Validator
- Object
- ActiveModel::Validator
- Gemgento::CreditCardValidator
- Defined in:
- app/validators/gemgento/credit_card_validator.rb
Instance Method Summary collapse
-
#card_number ⇒ Object
Validate credit card number with a Luhn test.
- #expiration_date ⇒ Object
- #security_code ⇒ Object
- #validate(record) ⇒ Object
Instance Method Details
#card_number ⇒ Object
Validate credit card number with a Luhn test. Based on rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#Ruby
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
# File 'app/validators/gemgento/credit_card_validator.rb', line 12 def card_number s1 = s2 = 0 cc_number = @record.cc_number.gsub(/\D/, '') # remove all white space cc_number.to_s.reverse.chars.each_slice(2) do |odd, even| s1 += odd.to_i double = even.to_i * 2 double -= 9 if double >= 10 s2 += double end if (s1 + s2) % 10 != 0 @record.errors[:cc_number] << 'is invalid' end end |
#expiration_date ⇒ Object
29 30 31 32 33 34 35 36 37 38 |
# File 'app/validators/gemgento/credit_card_validator.rb', line 29 def expiration_date year = @record.cc_exp_year.to_i month = @record.cc_exp_month.to_i if year < Time.now.year @record.errors[:cc_exp_month] = 'cannot be in the past' elsif (year == Time.now.year && month < Time.now.month) @record.errors[:cc_exp_month] = 'cannot be in the past' end end |
#security_code ⇒ Object
40 41 42 43 44 45 46 47 |
# File 'app/validators/gemgento/credit_card_validator.rb', line 40 def security_code if (@record.cc_cid.length < 3 || @record.cc_cid.length > 4) || # between 3 and 4 digits @record.cc_cid.gsub(/\D/, '') != @record.cc_cid || # numbers only !(1..9999).include?(@record.cc_cid.to_i) @record.errors[:cc_cid] << 'is invalid' end end |
#validate(record) ⇒ Object
3 4 5 6 7 8 |
# File 'app/validators/gemgento/credit_card_validator.rb', line 3 def validate(record) @record = record card_number expiration_date security_code end |