Advertisement
Guest User

Untitled

a guest
May 30th, 2015
251
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.44 KB | None | 0 0
  1. module ValidateSpanishVat
  2. module ClassMethods
  3. # Implements model level validator for Spanish's VAT number.
  4. # Usage:
  5. #
  6. # Inside a model with a vat field, simply put
  7. #
  8. # validates_spanish_vat field_name
  9. #
  10. def validates_spanish_vat(*attr_names)
  11. configuration = { :message => :invalid, :on => :save }
  12. configuration.update(attr_names.pop) if attr_names.last.is_a?(Hash)
  13.  
  14. validates_each(attr_names, configuration) do |record, attr_name, value|
  15. record.errors.add(attr_name, configuration[:message]) unless CustomValidator::SpanishVAT.validate(value)
  16. end
  17. end
  18. end
  19. end
  20.  
  21. module CustomValidator
  22. class SpanishVAT
  23. # Main validate function, it runs several regexp's to determine if value is a nif, cif or nie.
  24. # If so, it runs specific test, else fails
  25. def self.validate(model_value)
  26. return false if model_value.nil?
  27. value = model_value.clone
  28.  
  29. case
  30. when value.match(/[0-9]{8}[a-z]/i)
  31. return validate_nif(value)
  32. when value.match(/[a-wyz][0-9]{7}[0-9a-z]/i)
  33. return validate_cif(value)
  34. when value.match(/[x][0-9]{7,8}[a-z]/i)
  35. return validate_nie(value)
  36. end
  37. return false
  38. end
  39.  
  40. # Validates NIF
  41. def self.validate_nif(value)
  42. letters = "TRWAGMYFPDXBNJZSQVHLCKE"
  43. check = value.slice!(value.length - 1..value.length - 1).upcase
  44. calculated_letter = letters[value.to_i % 23].chr
  45. return check === calculated_letter
  46. end
  47.  
  48. # Validates CIF
  49. def self.validate_cif(value)
  50. letter = value.slice!(0).chr.upcase
  51. check = value.slice!(value.length - 1).chr.upcase
  52.  
  53. n1 = n2 = 0
  54. for idx in 0..value.length - 1
  55. number = value.slice!(0).chr.to_i
  56. if (idx % 2) != 0
  57. n1 += number
  58. else
  59. n2 += ((2*number) % 10) + ((2 * number) / 10)
  60. end
  61. end
  62. calculated_number = (10 - ((n1 + n2) % 10)) % 10
  63. calculated_letter = (64 + calculated_number).chr
  64.  
  65. if letter.match(/[QPNSW]/)
  66.  
  67. return check.to_s == calculated_letter.to_s
  68. else
  69.  
  70. return check.to_i == calculated_number.to_i
  71. end
  72. end
  73.  
  74. # Validates NIE, in fact is a fake, a NIE is really a NIF with first number changed to capital 'X' letter, so we change the first X to a 0 and then try to
  75. # pass the nif validator
  76. def self.validate_nie(value)
  77. value[0] = '0'
  78. value.slice(0) if value.size > 9
  79. validate_nif(value)
  80. end
  81. end
  82. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement