ngcpf
Version:
A module to validate and format cpf
82 lines • 3.04 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var core_1 = require("@angular/core");
var forms_1 = require("@angular/forms");
var CpfValidatorDirective = (function () {
function CpfValidatorDirective(validateCpf) {
this.validateCpf = validateCpf;
this.validator = this.validateCpfFactory();
}
CpfValidatorDirective.prototype.validate = function (c) {
return this.validator(c);
};
CpfValidatorDirective.prototype.validateCpfFactory = function () {
return function (c) {
var field = c.value, cpf, number, digit, sum, result, equalDigits = true;
cpf = field.replace(/(\.|\/|\-)/g, "");
if (cpf.length < 11 || cpf.length > 11) {
return {
validateCpf: {
valid: false
}
};
}
for (var i = 0; i < cpf.length - 1; i++) {
if (cpf.charAt(i) != cpf.charAt(i + 1)) {
equalDigits = false;
break;
}
}
if (equalDigits === false) {
number = cpf.substring(0, 9);
digit = cpf.substring(9);
sum = 0;
for (var i = 10; i > 1; i--) {
sum += number.charAt(10 - i) * i;
}
result = sum % 11 < 2 ? 0 : 11 - sum % 11;
if (result != digit.charAt(0)) {
return {
validateCpf: {
valid: false
}
};
}
number = cpf.substring(0, 10);
sum = 0;
for (var i = 11; i > 1; i--) {
sum += number.charAt(11 - i) * i;
}
result = sum % 11 < 2 ? 0 : 11 - sum % 11;
if (result != digit.charAt(1)) {
return {
validateCpf: {
valid: false
}
};
}
return null;
}
return {
validateCpf: {
valid: false
}
};
};
};
return CpfValidatorDirective;
}());
CpfValidatorDirective.decorators = [
{ type: core_1.Directive, args: [{
selector: '[validateCpf][ngModel],[validateCpf][formControl],[validateCpf][formControlName]',
providers: [
{ provide: forms_1.NG_VALIDATORS, useExisting: core_1.forwardRef(function () { return CpfValidatorDirective; }), multi: true }
]
},] },
];
/** @nocollapse */
CpfValidatorDirective.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: core_1.Attribute, args: ['validateCpf',] },] },
]; };
exports.CpfValidatorDirective = CpfValidatorDirective;
//# sourceMappingURL=cpf.directive.js.map