Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * exemplo de plugin jQuery
- *
- * @refer http://www.macoratti.net/alg_cpf.htm
- * @author J. Augusto <augustowebd.spam (a) gmail dot com
- * @date 2017-07-15
- */
- (function ($){
- /**
- * @code
- * $('inputSelector').validaCpf()
- * @code
- *
- * @param String msgError
- */
- $.fn.validaCpf = function (msgError) {
- let lenAction = 11;
- $(this)
- .on('keyup', function () {
- let rawValue = this.value;
- let cleanValue = rawValue.replace(/[^\d]/gi, '');
- if (cleanValue.length == lenAction) {
- if (! cpfAlgorithinValidate(cleanValue)) {
- throw Error(
- msgError
- ? msgError
- : 'Valor inválido'
- );
- }
- }
- })
- ;
- return this;
- };
- })(jQuery);
- let cpfAlgorithinValidate = function (val) {
- let digit_10 = val[val.length - 2];
- let digit_11 = val[val.length - 1];
- return (
- digit_10 === val.substr(0, 9).module11() &&
- digit_11 === val.substr(0, 10).module11()
- );
- };
- /**
- * Adiciona método de validacao de cpf à classe core.javascript.String
- *
- * @code
- * "123456789".module11();
- * "1234567890".module11();
- * @code
- *
- * @return string
- */
- String.prototype.module11 = function () {
- let sum = 0;
- let module11 = 11;
- let multiplier = this.length + 1;
- for (let i = 0; i < this.length; i++) {
- sum += (multiplier - i) * parseInt(this[i]);
- }
- let resultMod = sum % module11;
- let result = resultMod < 2
- ? 0
- : module11 - resultMod
- ;
- return result + '';
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement