Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- trigger onAccount on Account (before insert, before update) {
- for(Account a: Trigger.new){
- if(!Pattern.matches('[ABCDEFGHJKLMNPQRSUVW][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9A-J]', a.cif__c)){
- a.cif__c.addError('CIF wrong format');
- }else{
- if(!validateCif(a)){
- a.cif__c.addError('CIF invalid');
- }
- }
- }
- public boolean validateCif(Account a){
- String[] letters = new String[]{'J','A','B','C','D','E','F','G','H','I'};
- String digits = a.cif__c.substring(1, a.cif__c.length()-1);
- String letter = a.cif__c.substring(0,1);
- String control = a.cif__c.substring(a.cif__c.length() -1);
- Integer sum = 0;
- Integer i;
- Integer digit;
- for(i=0;i<digits.length();i++){
- digit = Integer.valueOf(digits.substring(i,i+1));
- system.debug('digit: '+digit);
- if(Math.mod(i, 2) == 0){
- digit *= 2;
- if(digit > 9){
- digit = (digit / 10) + (Math.mod(digit, 10));
- }
- sum += digit;
- }else{
- sum += digit;
- }
- }
- sum = Math.mod(sum, 10);
- if(sum != 0){
- digit = 10 - sum;
- }else{
- digit = sum;
- }
- if(Pattern.matches('[ABEH]', letter)){
- return String.valueOf(digit) == control;
- }
- if(Pattern.matches('[NPQRSW]', letter)){
- return letters[digit] == control;
- }
- return String.valueOf(digit) == control || letters[digit] == control;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement