Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. trigger onAccount on Account (before insert, before update) {
  2. for(Account a: Trigger.new){
  3. if(!Pattern.matches('[ABCDEFGHJKLMNPQRSUVW][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9A-J]', a.cif__c)){
  4. a.cif__c.addError('CIF wrong format');
  5. }else{
  6. if(!validateCif(a)){
  7. a.cif__c.addError('CIF invalid');
  8. }
  9. }
  10. }
  11.  
  12. public boolean validateCif(Account a){
  13. String[] letters = new String[]{'J','A','B','C','D','E','F','G','H','I'};
  14. String digits = a.cif__c.substring(1, a.cif__c.length()-1);
  15. String letter = a.cif__c.substring(0,1);
  16. String control = a.cif__c.substring(a.cif__c.length() -1);
  17. Integer sum = 0;
  18. Integer i;
  19. Integer digit;
  20.  
  21. for(i=0;i<digits.length();i++){
  22. digit = Integer.valueOf(digits.substring(i,i+1));
  23. system.debug('digit: '+digit);
  24.  
  25. if(Math.mod(i, 2) == 0){
  26. digit *= 2;
  27. if(digit > 9){
  28. digit = (digit / 10) + (Math.mod(digit, 10));
  29. }
  30. sum += digit;
  31. }else{
  32. sum += digit;
  33. }
  34. }
  35.  
  36. sum = Math.mod(sum, 10);
  37. if(sum != 0){
  38. digit = 10 - sum;
  39. }else{
  40. digit = sum;
  41. }
  42.  
  43. if(Pattern.matches('[ABEH]', letter)){
  44. return String.valueOf(digit) == control;
  45. }
  46. if(Pattern.matches('[NPQRSW]', letter)){
  47. return letters[digit] == control;
  48. }
  49. return String.valueOf(digit) == control || letters[digit] == control;
  50. }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement