Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

js-brasil

Package Overview
Dependencies
Maintainers
1
Versions
86
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

js-brasil - npm Package Compare versions

Comparing version 1.1.0 to 1.1.1

demo/cartao.html

10

dist/index.js

@@ -8,2 +8,5 @@ "use strict";

var mask = require("./src/mask");
var mask_1 = require("./src/mask");
var placa_1 = require("./src/placa");
var estados_1 = require("./src/estados");
exports.validateBr = {

@@ -17,3 +20,4 @@ cep: validate_1.valida_cep,

rg: validate_1.validate_rg,
placa: validate_1.validate_placa,
placa: placa_1.validate_placa,
renavam: validate_1.validate_renavam,
telefone: validate_1.validate_telefone,

@@ -27,3 +31,5 @@ celular: validate_1.validate_celular,

isPresent: utils_1.isPresent,
MASKS: utils_1.MASKS
MASKS: mask_1.MASKS,
PLACAS_RANGE: placa_1.PLACAS_RANGE,
ESTADOS: estados_1.ESTADOS
};

@@ -30,0 +36,0 @@ exports.maskBr = mask.maskBr;

82

dist/src/faker.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var utils_1 = require("./utils");
var estados_1 = require("./estados");
var mask_1 = require("./mask");
var validate_1 = require("./validate");
var randexp_1 = require("randexp");
var placa_1 = require("./placa");
var makeGeneric = function (val, options) {

@@ -25,5 +27,10 @@ if (options === void 0) { options = null; }

c = c.replace('/[', '').replace(']/', '').split('-');
var mult = c[1] - c[0];
var plus = parseInt(c[0]);
return (Math.floor(Math.random() * mult) + plus).toString();
if (parseInt(c[1])) {
var mult = c[1] - c[0];
var plus = parseInt(c[0]);
return (Math.floor(Math.random() * mult) + plus).toString();
}
else {
return rand(1, [c[0], c[1]]);
}
}

@@ -37,2 +44,17 @@ else {

};
function rand(length) {
var ranges = [];
for (var _i = 1; _i < arguments.length; _i++) {
ranges[_i - 1] = arguments[_i];
}
var str = ""; // the string (initialized to "")
while (length--) { // repeat this length of times
var ind = Math.floor(Math.random() * ranges.length); // get a random range from the ranges object
var min = ranges[ind][0].charCodeAt(0), // get the minimum char code allowed for this range
max = ranges[ind][1].charCodeAt(0); // get the maximum char code allowed for this range
var c = Math.floor(Math.random() * (max - min + 1)) + min; // get a random char code between min and max
str += String.fromCharCode(c); // convert it back into a character and append it to the string str
}
return str; // return str
}
function randomLetter(size, onlyCapitals) {

@@ -54,13 +76,7 @@ if (size === void 0) { size = 1; }

var randomEstadoSigla = function () {
var total = utils_1.ESTADOS_SIGLA.length;
return utils_1.ESTADOS_SIGLA[Math.floor(Math.random() * total)];
var total = estados_1.ESTADOS_SIGLA.length;
return estados_1.ESTADOS_SIGLA[Math.floor(Math.random() * total)];
};
var random = randomEstadoSigla();
random = random.split('');
var makeRg = makeGeneric(utils_1.MASKS['rg'], {
0: function () { return random[0]; },
1: function () { return random[1]; }
});
exports.fakerBr = {
cep: makeGeneric(utils_1.MASKS['cep']),
cep: makeGeneric(mask_1.MASKS['cep']),
cepState: function (state) {

@@ -70,3 +86,3 @@ return randexp_1.randexp(validate_1.CEPRange[state]);

cpf: function () {
var cpf = makeGeneric(utils_1.MASKS['cpf'])();
var cpf = makeGeneric(mask_1.MASKS['cpf'])();
var restos = validate_1.create_cpf(cpf);

@@ -78,3 +94,3 @@ cpf = cpf.substr(0, cpf.length - 2) + restos[0] + restos[1];

cnpj: function () {
var cnpj = makeGeneric(utils_1.MASKS['cnpj'])();
var cnpj = makeGeneric(mask_1.MASKS['cnpj'])();
cnpj = cnpj.replace(/[^\d]+/g, '');

@@ -86,13 +102,27 @@ var restos = validate_1.create_cnpj(cnpj);

},
rg: makeRg,
telefone: makeGeneric(utils_1.MASKS['telefone']),
celular: makeGeneric(utils_1.MASKS['celular']),
inscricaoestadual: makeGeneric(utils_1.MASKS['inscricaoestadual']),
time: makeGeneric(utils_1.MASKS['time']),
currency: makeGeneric(utils_1.MASKS['currency']),
percentage: makeGeneric(utils_1.MASKS['percentage']),
placa: makeGeneric(utils_1.MASKS['placa']),
processo: makeGeneric(utils_1.MASKS['processo']),
rg: function () {
var random = randomEstadoSigla();
random = random.split('');
var makeRg = makeGeneric(mask_1.MASKS['rg'], {
0: function () { return random[0]; },
1: function () { return random[1]; }
});
return makeRg();
},
telefone: makeGeneric(mask_1.MASKS['telefone']),
celular: makeGeneric(mask_1.MASKS['celular']),
inscricaoestadual: makeGeneric(mask_1.MASKS['inscricaoestadual']),
time: makeGeneric(mask_1.MASKS['time']),
currency: makeGeneric(mask_1.MASKS['currency']),
percentage: makeGeneric(mask_1.MASKS['percentage']),
placa: function () {
var placa;
do {
placa = makeGeneric(mask_1.MASKS['placa'])();
} while (!placa_1.validate_placa(placa));
return placa;
},
processo: makeGeneric(mask_1.MASKS['processo']),
titulo: function () {
var titulo = makeGeneric(utils_1.MASKS['titulo'])();
var titulo = makeGeneric(mask_1.MASKS['titulo'])();
var _a = validate_1.create_titulo(titulo), dig1 = _a.dig1, dig2 = _a.dig2;

@@ -102,3 +132,3 @@ return titulo.substr(0, titulo.length - 2) + dig1 + dig2;

renavam: function () {
var renavam = makeGeneric(utils_1.MASKS['renavam'])();
var renavam = makeGeneric(mask_1.MASKS['renavam'])();
var dv = validate_1.create_renavam(renavam);

@@ -105,0 +135,0 @@ return renavam.substr(0, renavam.length - 1) + dv;

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var utils_1 = require("./utils");
var inscricaoestadual_1 = require("./inscricaoestadual");
var createNumberMask_1 = require("text-mask-addons/dist/createNumberMask");
exports.MASKS = {
cpf: {
text: '000.000.000-00',
textMask: [/\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '-', /\d/, /\d/]
},
cnpj: {
text: '00.000.000/0000-00',
textMask: [/\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '/', /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/]
},
rg: {
text: 'AA-00.000.000',
textMask: [/[A-Za-z]/, /[A-Za-z]/, '-', /\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/]
},
telefone: {
text: '(00) 0000-0000',
textMask: ['(', /[1-9]/, /\d/, ')', ' ', /[1-9]/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/],
textMaskFunction: function mask(userInput) {
var numbers = userInput.match(/\d/g);
var numberLength = 0;
if (numbers) {
numberLength = numbers.join('').length;
}
if (!userInput || numberLength > 10) {
return ['(', /[1-9]/, /\d/, ')', ' ', /[1-9]/, /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/];
}
else {
return ['(', /[1-9]/, /\d/, ')', ' ', /[1-9]/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/];
}
}
},
celular: {
text: '(00) 00000-0000',
textMask: ['(', /[1-9]/, /\d/, ')', ' ', /[5-9]/, /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/],
},
cep: {
text: '00.000-000',
textMask: [/\d/, /\d/, '.', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/]
},
inscricaoestadual: inscricaoestadual_1.IEMASKS,
time: {
text: '00:00',
textMask: [/\d/, /\d/, ':', /\d/, /\d/]
},
currency: {
text: '0.000,00',
textMask: createNumberMask_1.default({
decimalLimit: 2,
thousandsSeparatorSymbol: '.',
decimalSymbol: ',',
allowDecimal: true,
integerLimit: 15,
prefix: 'R$ ',
suffix: ''
})
},
percentage: {
text: '00,00%',
textMask: createNumberMask_1.default({
decimalLimit: 2,
thousandsSeparatorSymbol: '.',
decimalSymbol: ',',
allowDecimal: true,
integerLimit: 15,
prefix: '',
suffix: '%'
})
},
placa: {
text: 'AAA-0000',
textMask: [/[A-S]/, /[A-Z]/, /[A-Z]/, '-', /\d/, /\d/, /\d/, /\d/]
},
titulo: {
text: '0000.0000.0000',
textMask: [/\d/, /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, /\d/]
},
processo: {
text: '0000000-00.0000.AAA.0000',
textMask: [/\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, '.', /\d/, /\d/, /\d/, /\d/, '.', /[A-Za-z]/, /[A-Za-z]/, /[A-Za-z]/, '.', /\d/, /\d/, /\d/, /\d/]
},
renavam: {
text: '0000000000-00',
textMask: [/\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/],
textMaskFunction: function mask(userInput) {
var numbers = userInput.match(/\d/g);
var numberLength = 0;
if (numbers) {
numberLength = numbers.join('').length;
}
if (!userInput || numberLength < 9) {
return [/\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/];
}
else {
return [/\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/];
}
}
}
};
var makeGeneric = function (key) {

@@ -9,7 +108,7 @@ return function (value) {

}
var mask = utils_1.MASKS[key].textMask;
if (utils_1.MASKS[key].textMaskFunction) {
mask = utils_1.MASKS[key].textMaskFunction(value);
var mask = exports.MASKS[key].textMask;
if (exports.MASKS[key].textMaskFunction) {
mask = exports.MASKS[key].textMaskFunction(value);
}
return utils_1.conformToMask(value, mask, { guide: false }).conformedValue;
return conformToMask(value, mask, { guide: false }).conformedValue;
};

@@ -25,7 +124,7 @@ };

inscricaoestadual: function (inscricaoestadualValue, estado) {
if (!inscricaoestadualValue || !estado || !utils_1.MASKS.inscricaoestadual[estado] ||
!utils_1.MASKS.inscricaoestadual[estado].textMask) {
if (!inscricaoestadualValue || !estado || !exports.MASKS.inscricaoestadual[estado] ||
!exports.MASKS.inscricaoestadual[estado].textMask) {
return '';
}
return utils_1.conformToMask(inscricaoestadualValue, utils_1.MASKS.inscricaoestadual[estado].textMask, { guide: false }).conformedValue;
return conformToMask(inscricaoestadualValue, exports.MASKS.inscricaoestadual[estado].textMask, { guide: false }).conformedValue;
},

@@ -37,5 +136,11 @@ time: makeGeneric('time'),

}
var vals = currencyValue.split(',');
var mask = utils_1.MASKS.currency.textMask(vals[0]);
return utils_1.conformToMask(currencyValue, mask, { guide: false }).conformedValue + ',' + vals[1];
if (currencyValue.split) {
var vals = currencyValue.split(',');
var mask = exports.MASKS.currency.textMask(vals[0]);
return conformToMask(currencyValue, mask, { guide: false }).conformedValue + ',' + vals[1];
}
else {
var mask = exports.MASKS.currency.textMask(currencyValue);
return conformToMask(currencyValue, mask, { guide: false }).conformedValue;
}
},

@@ -47,4 +152,4 @@ percentage: function (percentageValue) {

var vals = percentageValue.split(',');
var mask = utils_1.MASKS.percentage.textMask(vals[0]);
return utils_1.conformToMask(percentageValue, mask, { guide: false }).conformedValue + ',' + vals[1];
var mask = exports.MASKS.percentage.textMask(vals[0]);
return conformToMask(percentageValue, mask, { guide: false }).conformedValue + ',' + vals[1];
},

@@ -55,2 +160,238 @@ placa: makeGeneric('placa'),

};
/**
* FROM TEXT-MASK
*/
exports.placeholderChar = '_';
exports.strFunction = 'function';
var defaultPlaceholderChar = exports.placeholderChar;
var emptyArray = [];
var emptyString = '';
function conformToMask(rawValue, mask, config) {
if (rawValue === void 0) { rawValue = emptyString; }
if (mask === void 0) { mask = emptyArray; }
if (config === void 0) { config = {}; }
if (!utils_1.isArray(mask)) {
// If someone passes a function as the mask property, we should call the
// function to get the mask array - Normally this is handled by the
// `createTextMaskInputElement:update` function - this allows mask functions
// to be used directly with `conformToMask`
if (typeof mask === exports.strFunction) {
// call the mask function to get the mask array
mask = mask(rawValue, config);
// mask functions can setup caret traps to have some control over how the caret moves. We need to process
// the mask for any caret traps. `processCaretTraps` will remove the caret traps from the mask
mask = utils_1.processCaretTraps(mask).maskWithoutCaretTraps;
}
else {
throw new Error('Text-mask:conformToMask; The mask property must be an array.');
}
}
// These configurations tell us how to conform the mask
var guide = config.guide || true;
var previousConformedValue = config.previousConformedValue || emptyString;
var placeholder = convertMaskToPlaceholder(mask, exports.placeholderChar);
var currentCaretPosition = config.currentCaretPosition;
var keepCharPositions = config.keepCharPositions;
// The configs below indicate that the user wants the algorithm to work in *no guide* mode
var suppressGuide = guide === false && previousConformedValue !== undefined;
// Calculate lengths once for performance
var rawValueLength = rawValue.length;
var previousConformedValueLength = previousConformedValue.length;
var placeholderLength = placeholder.length;
var maskLength = mask.length;
// This tells us the number of edited characters and the direction in which they were edited (+/-)
var editDistance = rawValueLength - previousConformedValueLength;
// In *no guide* mode, we need to know if the user is trying to add a character or not
var isAddition = editDistance > 0;
// Tells us the index of the first change. For (438) 394-4938 to (38) 394-4938, that would be 1
var indexOfFirstChange = currentCaretPosition + (isAddition ? -editDistance : 0);
// We're also gonna need the index of last change, which we can derive as follows...
var indexOfLastChange = indexOfFirstChange + Math.abs(editDistance);
// If `conformToMask` is configured to keep character positions, that is, for mask 111, previous value
// _2_ and raw value 3_2_, the new conformed value should be 32_, not 3_2 (default behavior). That's in the case of
// addition. And in the case of deletion, previous value _23, raw value _3, the new conformed string should be
// __3, not _3_ (default behavior)
//
// The next block of logic handles keeping character positions for the case of deletion. (Keeping
// character positions for the case of addition is further down since it is handled differently.)
// To do this, we want to compensate for all characters that were deleted
if (keepCharPositions === true && !isAddition) {
// We will be storing the new placeholder characters in this variable.
var compensatingPlaceholderChars = emptyString;
// For every character that was deleted from a placeholder position, we add a placeholder char
for (var i = indexOfFirstChange; i < indexOfLastChange; i++) {
if (placeholder[i] === exports.placeholderChar) {
compensatingPlaceholderChars += exports.placeholderChar;
}
}
// Now we trick our algorithm by modifying the raw value to make it contain additional placeholder characters
// That way when the we start laying the characters again on the mask, it will keep the non-deleted characters
// in their positions.
rawValue = (rawValue.slice(0, indexOfFirstChange) +
compensatingPlaceholderChars +
rawValue.slice(indexOfFirstChange, rawValueLength));
}
// Convert `rawValue` string to an array, and mark characters based on whether they are newly added or have
// existed in the previous conformed value. Identifying new and old characters is needed for `conformToMask`
// to work if it is configured to keep character positions.
var rawValueArr = rawValue
.split(emptyString)
.map(function (char, i) { return ({ char: char, isNew: i >= indexOfFirstChange && i < indexOfLastChange }); });
// The loop below removes masking characters from user input. For example, for mask
// `00 (111)`, the placeholder would be `00 (___)`. If user input is `00 (234)`, the loop below
// would remove all characters but `234` from the `rawValueArr`. The rest of the algorithm
// then would lay `234` on top of the available placeholder positions in the mask.
for (var i = rawValueLength - 1; i >= 0; i--) {
var char = rawValueArr[i].char;
if (char !== exports.placeholderChar) {
var shouldOffset = i >= indexOfFirstChange && previousConformedValueLength === maskLength;
if (char === placeholder[(shouldOffset) ? i - editDistance : i]) {
rawValueArr.splice(i, 1);
}
}
}
// This is the variable that we will be filling with characters as we figure them out
// in the algorithm below
var conformedValue = emptyString;
var someCharsRejected = false;
// Ok, so first we loop through the placeholder looking for placeholder characters to fill up.
placeholderLoop: for (var i = 0; i < placeholderLength; i++) {
var charInPlaceholder = placeholder[i];
// We see one. Let's find out what we can put in it.
if (charInPlaceholder === exports.placeholderChar) {
// But before that, do we actually have any user characters that need a place?
if (rawValueArr.length > 0) {
// We will keep chipping away at user input until either we run out of characters
// or we find at least one character that we can map.
while (rawValueArr.length > 0) {
// Let's retrieve the first user character in the queue of characters we have left
var _a = rawValueArr.shift(), rawValueChar = _a.char, isNew = _a.isNew;
// If the character we got from the user input is a placeholder character (which happens
// regularly because user input could be something like (540) 90_-____, which includes
// a bunch of `_` which are placeholder characters) and we are not in *no guide* mode,
// then we map this placeholder character to the current spot in the placeholder
if (rawValueChar === exports.placeholderChar && suppressGuide !== true) {
conformedValue += exports.placeholderChar;
// And we go to find the next placeholder character that needs filling
continue placeholderLoop;
// Else if, the character we got from the user input is not a placeholder, let's see
// if the current position in the mask can accept it.
}
else if (mask[i].test(rawValueChar)) {
// we map the character differently based on whether we are keeping character positions or not.
// If any of the conditions below are met, we simply map the raw value character to the
// placeholder position.
if (keepCharPositions !== true ||
isNew === false ||
previousConformedValue === emptyString ||
guide === false ||
!isAddition) {
conformedValue += rawValueChar;
}
else {
// We enter this block of code if we are trying to keep character positions and none of the conditions
// above is met. In this case, we need to see if there's an available spot for the raw value character
// to be mapped to. If we couldn't find a spot, we will discard the character.
//
// For example, for mask `1111`, previous conformed value `_2__`, raw value `942_2__`. We can map the
// `9`, to the first available placeholder position, but then, there are no more spots available for the
// `4` and `2`. So, we discard them and end up with a conformed value of `92__`.
var rawValueArrLength = rawValueArr.length;
var indexOfNextAvailablePlaceholderChar = null;
// Let's loop through the remaining raw value characters. We are looking for either a suitable spot, ie,
// a placeholder character or a non-suitable spot, ie, a non-placeholder character that is not new.
// If we see a suitable spot first, we store its position and exit the loop. If we see a non-suitable
// spot first, we exit the loop and our `indexOfNextAvailablePlaceholderChar` will stay as `null`.
for (var i_1 = 0; i_1 < rawValueArrLength; i_1++) {
var charData = rawValueArr[i_1];
if (charData.char !== exports.placeholderChar && charData.isNew === false) {
break;
}
if (charData.char === exports.placeholderChar) {
indexOfNextAvailablePlaceholderChar = i_1;
break;
}
}
// If `indexOfNextAvailablePlaceholderChar` is not `null`, that means the character is not blocked.
// We can map it. And to keep the character positions, we remove the placeholder character
// from the remaining characters
if (indexOfNextAvailablePlaceholderChar !== null) {
conformedValue += rawValueChar;
rawValueArr.splice(indexOfNextAvailablePlaceholderChar, 1);
// If `indexOfNextAvailablePlaceholderChar` is `null`, that means the character is blocked. We have to
// discard it.
}
else {
i--;
}
}
// Since we've mapped this placeholder position. We move on to the next one.
continue placeholderLoop;
}
else {
someCharsRejected = true;
}
}
}
// We reach this point when we've mapped all the user input characters to placeholder
// positions in the mask. In *guide* mode, we append the left over characters in the
// placeholder to the `conformedString`, but in *no guide* mode, we don't wanna do that.
//
// That is, for mask `(111)` and user input `2`, we want to return `(2`, not `(2__)`.
if (suppressGuide === false) {
conformedValue += placeholder.substr(i, placeholderLength);
}
// And we break
break;
// Else, the charInPlaceholder is not a placeholderChar. That is, we cannot fill it
// with user input. So we just map it to the final output
}
else {
conformedValue += charInPlaceholder;
}
}
// The following logic is needed to deal with the case of deletion in *no guide* mode.
//
// Consider the silly mask `(111) /// 1`. What if user tries to delete the last placeholder
// position? Something like `(589) /// `. We want to conform that to `(589`. Not `(589) /// `.
// That's why the logic below finds the last filled placeholder character, and removes everything
// from that point on.
if (suppressGuide && isAddition === false) {
var indexOfLastFilledPlaceholderChar = null;
// Find the last filled placeholder position and substring from there
for (var i = 0; i < conformedValue.length; i++) {
if (placeholder[i] === exports.placeholderChar) {
indexOfLastFilledPlaceholderChar = i;
}
}
if (indexOfLastFilledPlaceholderChar !== null) {
// We substring from the beginning until the position after the last filled placeholder char.
conformedValue = conformedValue.substr(0, indexOfLastFilledPlaceholderChar + 1);
}
else {
// If we couldn't find `indexOfLastFilledPlaceholderChar` that means the user deleted
// the first character in the mask. So we return an empty string.
conformedValue = emptyString;
}
}
return { conformedValue: conformedValue, meta: { someCharsRejected: someCharsRejected } };
}
exports.conformToMask = conformToMask;
function convertMaskToPlaceholder(mask, placeholderChar) {
if (mask === void 0) { mask = emptyArray; }
if (placeholderChar === void 0) { placeholderChar = defaultPlaceholderChar; }
if (!utils_1.isArray(mask)) {
throw new Error('Text-mask:convertMaskToPlaceholder; The mask property must be an array.');
}
if (mask.indexOf(placeholderChar) !== -1) {
throw new Error('Placeholder character must not be used as part of the mask. Please specify a character ' +
'that is not present in your mask as your placeholder character.\n\n' +
("The placeholder character that was received is: " + JSON.stringify(placeholderChar) + "\n\n") +
("The mask that was received is: " + JSON.stringify(mask)));
}
return mask.map(function (char) {
return (char instanceof RegExp) ? placeholderChar : char;
}).join('');
}
exports.convertMaskToPlaceholder = convertMaskToPlaceholder;
//# sourceMappingURL=mask.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var inscricaoestadual_1 = require("./inscricaoestadual");
var createNumberMask_1 = require("text-mask-addons/dist/createNumberMask");
exports.ESTADOS_SIGLA = ['ac', 'al', 'am', 'ap', 'ba', 'ce', 'df', 'es', 'go', 'ma',
'mg', 'ms', 'mt', 'pa', 'pb', 'pe', 'pi', 'pr', 'rj', 'rn', 'ro', 'rr', 'rs',
'sc', 'se', 'sp', 'to'
];
exports.MASKS = {
cpf: {
text: '000.000.000-00',
textMask: [/\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '-', /\d/, /\d/]
},
cnpj: {
text: '00.000.000/0000-00',
textMask: [/\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '/', /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/]
},
rg: {
text: 'AA-00.000.000',
textMask: [/[A-Za-z]/, /[A-Za-z]/, '-', /\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/]
},
telefone: {
text: '(00) 0000-0000',
textMask: ['(', /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/],
textMaskFunction: function mask(userInput) {
var numbers = userInput.match(/\d/g);
var numberLength = 0;
if (numbers) {
numberLength = numbers.join('').length;
}
if (!userInput || numberLength > 10) {
return ['(', /[1-9]/, /\d/, ')', ' ', /[1-9]/, /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/];
}
else {
return ['(', /[1-9]/, /\d/, ')', ' ', /[1-9]/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/];
}
}
},
celular: {
text: '(00) 00000-0000',
textMask: ['(', /[1-9]/, /\d/, ')', ' ', /[5-9]/, /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/],
},
cep: {
text: '00.000-000',
textMask: [/\d/, /\d/, '.', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/]
},
inscricaoestadual: inscricaoestadual_1.IEMASKS,
time: {
text: '00:00',
textMask: [/\d/, /\d/, ':', /\d/, /\d/]
},
currency: {
text: '0.000,00',
textMask: createNumberMask_1.default({
decimalLimit: 2,
thousandsSeparatorSymbol: '.',
decimalSymbol: ',',
allowDecimal: true,
integerLimit: 15,
prefix: 'R$ ',
suffix: ''
})
},
percentage: {
text: '00,00%',
textMask: createNumberMask_1.default({
decimalLimit: 2,
thousandsSeparatorSymbol: '.',
decimalSymbol: ',',
allowDecimal: true,
integerLimit: 15,
prefix: '',
suffix: '%'
})
},
placa: {
text: 'AAA-0000',
textMask: [/[A-Za-z]/, /[A-Za-z]/, /[A-Za-z]/, '-', /\d/, /\d/, /\d/, /\d/]
},
titulo: {
text: '0000.0000.0000',
textMask: [/\d/, /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, /\d/]
},
processo: {
text: '0000000-00.0000.AAA.0000',
textMask: [/\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, '.', /\d/, /\d/, /\d/, /\d/, '.', /[A-Za-z]/, /[A-Za-z]/, /[A-Za-z]/, '.', /\d/, /\d/, /\d/, /\d/]
},
renavam: {
textMaskFunction: function mask(userInput) {
var numbers = userInput.match(/\d/g);
var numberLength = 0;
if (numbers) {
numberLength = numbers.join('').length;
}
if (!userInput || numberLength < 9) {
return [/\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/];
}
else {
return [/\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/];
}
}
}
};
function isPresent(obj) {

@@ -108,238 +7,2 @@ return obj !== undefined && obj !== null;

exports.isPresent = isPresent;
/**
* FROM TEXT-MASK
*/
exports.placeholderChar = '_';
exports.strFunction = 'function';
var defaultPlaceholderChar = exports.placeholderChar;
var emptyArray = [];
var emptyString = '';
function conformToMask(rawValue, mask, config) {
if (rawValue === void 0) { rawValue = emptyString; }
if (mask === void 0) { mask = emptyArray; }
if (config === void 0) { config = {}; }
if (!isArray(mask)) {
// If someone passes a function as the mask property, we should call the
// function to get the mask array - Normally this is handled by the
// `createTextMaskInputElement:update` function - this allows mask functions
// to be used directly with `conformToMask`
if (typeof mask === exports.strFunction) {
// call the mask function to get the mask array
mask = mask(rawValue, config);
// mask functions can setup caret traps to have some control over how the caret moves. We need to process
// the mask for any caret traps. `processCaretTraps` will remove the caret traps from the mask
mask = processCaretTraps(mask).maskWithoutCaretTraps;
}
else {
throw new Error('Text-mask:conformToMask; The mask property must be an array.');
}
}
// These configurations tell us how to conform the mask
var guide = config.guide || true;
var previousConformedValue = config.previousConformedValue || emptyString;
var placeholder = convertMaskToPlaceholder(mask, exports.placeholderChar);
var currentCaretPosition = config.currentCaretPosition;
var keepCharPositions = config.keepCharPositions;
// The configs below indicate that the user wants the algorithm to work in *no guide* mode
var suppressGuide = guide === false && previousConformedValue !== undefined;
// Calculate lengths once for performance
var rawValueLength = rawValue.length;
var previousConformedValueLength = previousConformedValue.length;
var placeholderLength = placeholder.length;
var maskLength = mask.length;
// This tells us the number of edited characters and the direction in which they were edited (+/-)
var editDistance = rawValueLength - previousConformedValueLength;
// In *no guide* mode, we need to know if the user is trying to add a character or not
var isAddition = editDistance > 0;
// Tells us the index of the first change. For (438) 394-4938 to (38) 394-4938, that would be 1
var indexOfFirstChange = currentCaretPosition + (isAddition ? -editDistance : 0);
// We're also gonna need the index of last change, which we can derive as follows...
var indexOfLastChange = indexOfFirstChange + Math.abs(editDistance);
// If `conformToMask` is configured to keep character positions, that is, for mask 111, previous value
// _2_ and raw value 3_2_, the new conformed value should be 32_, not 3_2 (default behavior). That's in the case of
// addition. And in the case of deletion, previous value _23, raw value _3, the new conformed string should be
// __3, not _3_ (default behavior)
//
// The next block of logic handles keeping character positions for the case of deletion. (Keeping
// character positions for the case of addition is further down since it is handled differently.)
// To do this, we want to compensate for all characters that were deleted
if (keepCharPositions === true && !isAddition) {
// We will be storing the new placeholder characters in this variable.
var compensatingPlaceholderChars = emptyString;
// For every character that was deleted from a placeholder position, we add a placeholder char
for (var i = indexOfFirstChange; i < indexOfLastChange; i++) {
if (placeholder[i] === exports.placeholderChar) {
compensatingPlaceholderChars += exports.placeholderChar;
}
}
// Now we trick our algorithm by modifying the raw value to make it contain additional placeholder characters
// That way when the we start laying the characters again on the mask, it will keep the non-deleted characters
// in their positions.
rawValue = (rawValue.slice(0, indexOfFirstChange) +
compensatingPlaceholderChars +
rawValue.slice(indexOfFirstChange, rawValueLength));
}
// Convert `rawValue` string to an array, and mark characters based on whether they are newly added or have
// existed in the previous conformed value. Identifying new and old characters is needed for `conformToMask`
// to work if it is configured to keep character positions.
var rawValueArr = rawValue
.split(emptyString)
.map(function (char, i) { return ({ char: char, isNew: i >= indexOfFirstChange && i < indexOfLastChange }); });
// The loop below removes masking characters from user input. For example, for mask
// `00 (111)`, the placeholder would be `00 (___)`. If user input is `00 (234)`, the loop below
// would remove all characters but `234` from the `rawValueArr`. The rest of the algorithm
// then would lay `234` on top of the available placeholder positions in the mask.
for (var i = rawValueLength - 1; i >= 0; i--) {
var char = rawValueArr[i].char;
if (char !== exports.placeholderChar) {
var shouldOffset = i >= indexOfFirstChange && previousConformedValueLength === maskLength;
if (char === placeholder[(shouldOffset) ? i - editDistance : i]) {
rawValueArr.splice(i, 1);
}
}
}
// This is the variable that we will be filling with characters as we figure them out
// in the algorithm below
var conformedValue = emptyString;
var someCharsRejected = false;
// Ok, so first we loop through the placeholder looking for placeholder characters to fill up.
placeholderLoop: for (var i = 0; i < placeholderLength; i++) {
var charInPlaceholder = placeholder[i];
// We see one. Let's find out what we can put in it.
if (charInPlaceholder === exports.placeholderChar) {
// But before that, do we actually have any user characters that need a place?
if (rawValueArr.length > 0) {
// We will keep chipping away at user input until either we run out of characters
// or we find at least one character that we can map.
while (rawValueArr.length > 0) {
// Let's retrieve the first user character in the queue of characters we have left
var _a = rawValueArr.shift(), rawValueChar = _a.char, isNew = _a.isNew;
// If the character we got from the user input is a placeholder character (which happens
// regularly because user input could be something like (540) 90_-____, which includes
// a bunch of `_` which are placeholder characters) and we are not in *no guide* mode,
// then we map this placeholder character to the current spot in the placeholder
if (rawValueChar === exports.placeholderChar && suppressGuide !== true) {
conformedValue += exports.placeholderChar;
// And we go to find the next placeholder character that needs filling
continue placeholderLoop;
// Else if, the character we got from the user input is not a placeholder, let's see
// if the current position in the mask can accept it.
}
else if (mask[i].test(rawValueChar)) {
// we map the character differently based on whether we are keeping character positions or not.
// If any of the conditions below are met, we simply map the raw value character to the
// placeholder position.
if (keepCharPositions !== true ||
isNew === false ||
previousConformedValue === emptyString ||
guide === false ||
!isAddition) {
conformedValue += rawValueChar;
}
else {
// We enter this block of code if we are trying to keep character positions and none of the conditions
// above is met. In this case, we need to see if there's an available spot for the raw value character
// to be mapped to. If we couldn't find a spot, we will discard the character.
//
// For example, for mask `1111`, previous conformed value `_2__`, raw value `942_2__`. We can map the
// `9`, to the first available placeholder position, but then, there are no more spots available for the
// `4` and `2`. So, we discard them and end up with a conformed value of `92__`.
var rawValueArrLength = rawValueArr.length;
var indexOfNextAvailablePlaceholderChar = null;
// Let's loop through the remaining raw value characters. We are looking for either a suitable spot, ie,
// a placeholder character or a non-suitable spot, ie, a non-placeholder character that is not new.
// If we see a suitable spot first, we store its position and exit the loop. If we see a non-suitable
// spot first, we exit the loop and our `indexOfNextAvailablePlaceholderChar` will stay as `null`.
for (var i_1 = 0; i_1 < rawValueArrLength; i_1++) {
var charData = rawValueArr[i_1];
if (charData.char !== exports.placeholderChar && charData.isNew === false) {
break;
}
if (charData.char === exports.placeholderChar) {
indexOfNextAvailablePlaceholderChar = i_1;
break;
}
}
// If `indexOfNextAvailablePlaceholderChar` is not `null`, that means the character is not blocked.
// We can map it. And to keep the character positions, we remove the placeholder character
// from the remaining characters
if (indexOfNextAvailablePlaceholderChar !== null) {
conformedValue += rawValueChar;
rawValueArr.splice(indexOfNextAvailablePlaceholderChar, 1);
// If `indexOfNextAvailablePlaceholderChar` is `null`, that means the character is blocked. We have to
// discard it.
}
else {
i--;
}
}
// Since we've mapped this placeholder position. We move on to the next one.
continue placeholderLoop;
}
else {
someCharsRejected = true;
}
}
}
// We reach this point when we've mapped all the user input characters to placeholder
// positions in the mask. In *guide* mode, we append the left over characters in the
// placeholder to the `conformedString`, but in *no guide* mode, we don't wanna do that.
//
// That is, for mask `(111)` and user input `2`, we want to return `(2`, not `(2__)`.
if (suppressGuide === false) {
conformedValue += placeholder.substr(i, placeholderLength);
}
// And we break
break;
// Else, the charInPlaceholder is not a placeholderChar. That is, we cannot fill it
// with user input. So we just map it to the final output
}
else {
conformedValue += charInPlaceholder;
}
}
// The following logic is needed to deal with the case of deletion in *no guide* mode.
//
// Consider the silly mask `(111) /// 1`. What if user tries to delete the last placeholder
// position? Something like `(589) /// `. We want to conform that to `(589`. Not `(589) /// `.
// That's why the logic below finds the last filled placeholder character, and removes everything
// from that point on.
if (suppressGuide && isAddition === false) {
var indexOfLastFilledPlaceholderChar = null;
// Find the last filled placeholder position and substring from there
for (var i = 0; i < conformedValue.length; i++) {
if (placeholder[i] === exports.placeholderChar) {
indexOfLastFilledPlaceholderChar = i;
}
}
if (indexOfLastFilledPlaceholderChar !== null) {
// We substring from the beginning until the position after the last filled placeholder char.
conformedValue = conformedValue.substr(0, indexOfLastFilledPlaceholderChar + 1);
}
else {
// If we couldn't find `indexOfLastFilledPlaceholderChar` that means the user deleted
// the first character in the mask. So we return an empty string.
conformedValue = emptyString;
}
}
return { conformedValue: conformedValue, meta: { someCharsRejected: someCharsRejected } };
}
exports.conformToMask = conformToMask;
function convertMaskToPlaceholder(mask, placeholderChar) {
if (mask === void 0) { mask = emptyArray; }
if (placeholderChar === void 0) { placeholderChar = defaultPlaceholderChar; }
if (!isArray(mask)) {
throw new Error('Text-mask:convertMaskToPlaceholder; The mask property must be an array.');
}
if (mask.indexOf(placeholderChar) !== -1) {
throw new Error('Placeholder character must not be used as part of the mask. Please specify a character ' +
'that is not present in your mask as your placeholder character.\n\n' +
("The placeholder character that was received is: " + JSON.stringify(placeholderChar) + "\n\n") +
("The mask that was received is: " + JSON.stringify(mask)));
}
return mask.map(function (char) {
return (char instanceof RegExp) ? placeholderChar : char;
}).join('');
}
exports.convertMaskToPlaceholder = convertMaskToPlaceholder;
function isArray(value) {

@@ -372,2 +35,14 @@ return (Array.isArray && Array.isArray(value)) || value instanceof Array;

exports.processCaretTraps = processCaretTraps;
exports.modulo11 = function (string, size, mod) {
var soma = 0;
for (var i = 1; i <= size; i++) {
// tslint:disable-next-line:radix
soma = soma + parseInt(string.substring(i - 1, i)) * (mod - i);
}
var resto = (soma * 10) % 11;
if ((resto === 10) || (resto === 11)) {
resto = 0;
}
return resto;
};
//# sourceMappingURL=utils.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var utils_1 = require("./utils");
// http://www.geradorcnpj.com/javascript-validar-cnpj.htm

@@ -84,27 +85,9 @@ /*

strCPF = strCPF.replace(/[^\d]+/g, '');
var soma;
var resto;
soma = 0;
if (strCPF === '00000000000') {
return false;
}
for (var i = 1; i <= 9; i++) {
// tslint:disable-next-line:radix
soma = soma + parseInt(strCPF.substring(i - 1, i)) * (11 - i);
}
resto = (soma * 10) % 11;
if ((resto === 10) || (resto === 11)) {
resto = 0;
}
var restos = [];
restos.push(resto);
soma = 0;
for (var i = 1; i <= 10; i++) {
soma = soma + parseInt(strCPF.substring(i - 1, i), 10) * (12 - i);
}
resto = (soma * 10) % 11;
if ((resto === 10) || (resto === 11)) {
resto = 0;
}
restos.push(resto);
var restos = [
utils_1.modulo11(strCPF, 9, 11),
utils_1.modulo11(strCPF, 10, 12)
];
return restos;

@@ -175,7 +158,2 @@ }

}
// const exp = /\(\d{2}\)\ \d{4}\-\d{4}/;
// const exp5 = /\(\d{2}\)\ \d{5}\-\d{4}/;
// if (!exp.test(tel) && !exp5.test(tel)) {
// return false;
// }
return true;

@@ -186,4 +164,4 @@ }

var celClean = cel.replace(/[^\d]+/g, '');
cel = cel.replace(/_/g, '');
if (!(celClean.length === 10 || celClean.length === 11)) {
celClean = celClean.replace(/_/g, '');
if (celClean.length !== 11) {
return false;

@@ -224,13 +202,2 @@ }

exports.validate_percentage = validate_percentage;
function validate_placa(placa) {
var placaClean = placa.replace(/-/g, '');
var exp = /[A-Za-z]{3}\-\d{4}/;
var expClean = /[A-Za-z]{3}\d{4}/;
// const letters = placa.substr(0, 3).toUpperCase();
if (!exp.test(placa) && !expClean.test(placaClean)) {
return false;
}
return true;
}
exports.validate_placa = validate_placa;
function validate_titulo(titulo) {

@@ -322,6 +289,2 @@ var tituloClean = titulo.replace(/\./g, '');

renavamClean = renavamClean.replace(/\-/g, '');
// const expClean = /\d{10}\d{4}\d{4}/;
// if (!exp.test(renavamClean) && !expClean.test(renavamClean)) {
// return false;
// }
var dv = create_renavam(renavam);

@@ -340,6 +303,5 @@ var tam = renavam.length;

var dig1 = 0;
var tam = renavam.length;
renavam = renavam.substr(0, tam - 2);
renavam = '000000000000' + renavam;
renavam = renavam.substr(renavam.length - 11, renavam.length - 1);
while (renavam.length < 11) {
renavam = '0' + renavam;
}
dig1 = (renavam.charCodeAt(0) - 48) * 3 + (renavam.charCodeAt(1) - 48) * 2 + (renavam.charCodeAt(2) - 48) * 9 + (renavam.charCodeAt(3) - 48) * 8 +

@@ -346,0 +308,0 @@ (renavam.charCodeAt(4) - 48) * 7 + (renavam.charCodeAt(5) - 48) * 6 + (renavam.charCodeAt(6) - 48) * 5 +

@@ -45,3 +45,2 @@ "use strict";

var celular = index_1.fakerBr.celular();
console.log(celular);
chai_1.expect(index_1.validateBr.celular(celular)).to.be.true;

@@ -48,0 +47,0 @@ });

@@ -14,2 +14,4 @@ "use strict";

chai_1.expect(index_1.validateBr.cpf('127.529.875-36')).to.be.true;
chai_1.expect(index_1.validateBr.cpf('127.529.875-46')).to.be.false;
chai_1.expect(index_1.validateBr.cpf('127.529.875-37')).to.be.false;
});

@@ -22,4 +24,11 @@ it('RG', function () {

});
it('PLACA', function () {
chai_1.expect(index_1.validateBr.placa('ABC1234')).to.be.true;
chai_1.expect(index_1.validateBr.placa('SAW0002')).to.be.false;
});
it('RENAVAM', function () {
chai_1.expect(index_1.validateBr.renavam('72176426415')).to.be.true;
chai_1.expect(index_1.validateBr.renavam('72176426415')).to.be.true;
});
it('Telefone', function () {
chai_1.expect(index_1.validateBr.telefone('31 999876767')).to.be.true;
chai_1.expect(index_1.validateBr.telefone('31 99876767')).to.be.true;

@@ -29,2 +38,8 @@ chai_1.expect(index_1.validateBr.telefone('(90) 1057-1600')).to.be.true;

});
it('Celular', function () {
// expect(validateBr.celular('31 999876767')).to.be.true;
chai_1.expect(index_1.validateBr.celular('31 99876767')).to.be.false;
// expect(validateBr.celular('(90) 1057-1600')).to.be.true;
// expect(validateBr.celular('(90) 00057-1600')).to.be.false;
});
it('TITULO', function () {

@@ -47,2 +62,3 @@ chai_1.expect(index_1.validateBr.titulo('6490.8084.4421')).to.be.true;

chai_1.expect(index_1.validateBr.telefone('1234')).to.be.false;
chai_1.expect(index_1.validateBr.celular('1234')).to.be.false;
chai_1.expect(index_1.validateBr.time('1234')).to.be.false;

@@ -49,0 +65,0 @@ chai_1.expect(index_1.validateBr.titulo('1234')).to.be.false;

import {
isPresent, MASKS
isPresent
} from './src/utils';
import {
valida_cep, validate_cnpj, validate_cpf, validate_telefone,
validate_placa, validate_currency, validate_percentage, validate_rg, validate_time, validate_titulo, validate_processo, validate_celular
validate_currency, validate_percentage, validate_rg, validate_time, validate_titulo, validate_processo, validate_celular, validate_renavam
} from './src/validate';

@@ -11,2 +11,5 @@ import { validar } from './src/inscricaoestadual';

import * as mask from './src/mask';
import { MASKS } from './src/mask';
import { PLACAS_RANGE, validate_placa } from './src/placa';
import { ESTADOS } from './src/estados';

@@ -22,2 +25,3 @@ export const validateBr = {

placa: validate_placa,
renavam: validate_renavam,
telefone: validate_telefone,

@@ -32,3 +36,5 @@ celular: validate_celular,

isPresent,
MASKS
MASKS,
PLACAS_RANGE,
ESTADOS
};

@@ -35,0 +41,0 @@

{
"name": "js-brasil",
"version": "1.1.0",
"version": "1.1.1",
"description": "Javascript Utils para Brasil (cpf, cnpj...)",

@@ -13,3 +13,5 @@ "main": "dist/index.js",

"dist": "npm run build && npm run browserify",
"publish-npm": "npm run dist && npm publish"
"publish-npm": "npm run dist && npm publish",
"demo": "cp js-brasil.js demo/ && cd demo && http-server",
"demo-full": "npm run dist && cp js-brasil.js demo/ && cd demo && http-server"
},

@@ -16,0 +18,0 @@ "repository": {

@@ -15,4 +15,7 @@ # js-brasil

Módilos ValidateBR, MaskBR e FakerBR
Módilos ValidateBR, MaskBR e FakerBR para nodejs ou browser.
Veja tudo em ação no Gerador Brasileiro - http://geradorbrasileiro.com/
# ValidateBR

@@ -22,3 +25,3 @@

Javascript:
Node:
```js

@@ -48,3 +51,3 @@ const { validateBr } = require('js-brasil');

Javascript:
Node:
```js

@@ -79,3 +82,3 @@ const { maskBr } = require('js-brasil');

Javascript:
Node:
```js

@@ -102,20 +105,20 @@ const { fakerBr } = require('js-brasil');

* cep
* cnpj
* cpf
* currency
* inscricaoestadual - Todos os estados do Brasil
* percentage
* rg
* placa de carro
* telefone
* celular
* time
* titulo de eleitor
* processo da justiça
* CEP - http://geradorbrasileiro.com/cep.html
* CNPJ - http://geradorbrasileiro.com/cnpj.html
* CPF - - http://geradorbrasileiro.com/cpf.html
* Inscricao Estadual - - http://geradorbrasileiro.com/inscricaoestadual.html Todos os estados do Brasil
* RG - http://geradorbrasileiro.com/rg.html
* Placa de carro - http://geradorbrasileiro.com/placa.html
* Telefone - http://geradorbrasileiro.com/telefone.html
* Celular - http://geradorbrasileiro.com/celular.html
* Título de Eleitor - http://geradorbrasileiro.com/titulo.html
* Processo da justiça - http://geradorbrasileiro.com/processo.html
* Outros: currency, percentage, time (data/hora) - http://geradorbrasileiro.com/others.html
Utilizado pelo projeto
# Angular
Utilize em angular 6 com:
* ng-brazil - angular support for brazil apps - https://github.com/mariohmol/ng-brazil

@@ -1,4 +0,6 @@

import { MASKS, ESTADOS_SIGLA } from './utils';
import { ESTADOS_SIGLA } from './estados';
import { MASKS } from './mask';
import { create_cpf, create_cnpj, CEPRange, create_titulo, create_renavam } from './validate';
import { randexp } from 'randexp';
import { validate_placa } from './placa';

@@ -21,5 +23,9 @@ const makeGeneric = (val, options = null) => {

c = c.replace('/[', '').replace(']/', '').split('-')
const mult = c[1] - c[0];
const plus = parseInt(c[0]);
return (Math.floor(Math.random() * mult) + plus).toString();
if (parseInt(c[1])) {
const mult = c[1] - c[0];
const plus = parseInt(c[0]);
return (Math.floor(Math.random() * mult) + plus).toString();
} else {
return rand(1, [c[0], c[1]]);
}
} else {

@@ -33,2 +39,14 @@ return c;

function rand(length, ...ranges) {
var str = ""; // the string (initialized to "")
while (length--) { // repeat this length of times
var ind = Math.floor(Math.random() * ranges.length); // get a random range from the ranges object
var min = ranges[ind][0].charCodeAt(0), // get the minimum char code allowed for this range
max = ranges[ind][1].charCodeAt(0); // get the maximum char code allowed for this range
var c = Math.floor(Math.random() * (max - min + 1)) + min; // get a random char code between min and max
str += String.fromCharCode(c); // convert it back into a character and append it to the string str
}
return str; // return str
}
function randomLetter(size = 1, onlyCapitals = false) {

@@ -53,9 +71,4 @@ var text = "";

let random: any = randomEstadoSigla();
random = random.split('');
const makeRg = makeGeneric(MASKS['rg'], {
0: () => random[0],
1: () => random[1]
});
export const fakerBr = {

@@ -83,3 +96,11 @@ cep: makeGeneric(MASKS['cep']),

},
rg: makeRg,
rg: () => {
let random: any = randomEstadoSigla();
random = random.split('');
const makeRg = makeGeneric(MASKS['rg'], {
0: () => random[0],
1: () => random[1]
});
return makeRg();
},
telefone: makeGeneric(MASKS['telefone']),

@@ -91,3 +112,9 @@ celular: makeGeneric(MASKS['celular']),

percentage: makeGeneric(MASKS['percentage']),
placa: makeGeneric(MASKS['placa']),
placa: () => {
let placa;
do {
placa = makeGeneric(MASKS['placa'])();
} while (!validate_placa(placa));
return placa;
},
processo: makeGeneric(MASKS['processo']),

@@ -94,0 +121,0 @@ titulo: () => {

@@ -1,3 +0,102 @@

import { MASKS, conformToMask } from './utils';
import { isArray, processCaretTraps } from './utils';
import { IEMASKS } from './inscricaoestadual';
import createNumberMask from 'text-mask-addons/dist/createNumberMask'
export const MASKS = {
cpf: {
text: '000.000.000-00',
textMask: [/\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '-', /\d/, /\d/]
},
cnpj: {
text: '00.000.000/0000-00',
textMask: [/\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '/', /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/]
},
rg: {
text: 'AA-00.000.000',
textMask: [/[A-Za-z]/, /[A-Za-z]/, '-', /\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/]
},
telefone: {
text: '(00) 0000-0000',
textMask: ['(', /[1-9]/, /\d/, ')', ' ', /[1-9]/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/],
textMaskFunction: function mask(userInput) {
const numbers = userInput.match(/\d/g);
let numberLength = 0;
if (numbers) {
numberLength = numbers.join('').length;
}
if (!userInput || numberLength > 10) {
return ['(', /[1-9]/, /\d/, ')', ' ', /[1-9]/, /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/];
} else {
return ['(', /[1-9]/, /\d/, ')', ' ', /[1-9]/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/];
}
}
},
celular: {
text: '(00) 00000-0000',
textMask: ['(', /[1-9]/, /\d/, ')', ' ', /[5-9]/, /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/],
},
cep: {
text: '00.000-000',
textMask: [/\d/, /\d/, '.', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/]
},
inscricaoestadual: IEMASKS,
time: {
text: '00:00',
textMask: [/\d/, /\d/, ':', /\d/, /\d/]
},
currency: {
text: '0.000,00',
textMask: createNumberMask({
decimalLimit: 2,
thousandsSeparatorSymbol: '.',
decimalSymbol: ',',
allowDecimal: true,
integerLimit: 15,
prefix: 'R$ ',
suffix: ''
})
},
percentage: {
text: '00,00%',
textMask: createNumberMask({
decimalLimit: 2,
thousandsSeparatorSymbol: '.',
decimalSymbol: ',',
allowDecimal: true,
integerLimit: 15,
prefix: '',
suffix: '%'
})
},
placa: {
text: 'AAA-0000',
textMask: [/[A-S]/, /[A-Z]/, /[A-Z]/, '-', /\d/, /\d/, /\d/, /\d/]
},
titulo: {
text: '0000.0000.0000',
textMask: [/\d/, /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, /\d/]
},
processo: {
text: '0000000-00.0000.AAA.0000',
textMask: [/\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, '.', /\d/, /\d/, /\d/, /\d/, '.', /[A-Za-z]/, /[A-Za-z]/, /[A-Za-z]/, '.', /\d/, /\d/, /\d/, /\d/]
},
renavam: {
text: '0000000000-00',
textMask: [/\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/],
textMaskFunction: function mask(userInput) {
const numbers = userInput.match(/\d/g);
let numberLength = 0;
if (numbers) {
numberLength = numbers.join('').length;
}
if (!userInput || numberLength < 9) {
return [/\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/];
} else {
return [/\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/];
}
}
}
}
const makeGeneric = (key) => {

@@ -44,10 +143,22 @@ return (value) => {

}
const vals = currencyValue.split(',');
const mask = MASKS.currency.textMask(vals[0]);
if (currencyValue.split) {
const vals = currencyValue.split(',');
const mask = MASKS.currency.textMask(vals[0]);
return conformToMask(
currencyValue,
mask,
{ guide: false }
).conformedValue + ',' + vals[1];
return conformToMask(
currencyValue,
mask,
{ guide: false }
).conformedValue + ',' + vals[1];
} else {
const mask = MASKS.currency.textMask(currencyValue);
return conformToMask(
currencyValue,
mask,
{ guide: false }
).conformedValue;
}
},

@@ -71,1 +182,277 @@ percentage: (percentageValue) => {

};
/**
* FROM TEXT-MASK
*/
export const placeholderChar = '_'
export const strFunction = 'function'
const defaultPlaceholderChar = placeholderChar;
const emptyArray: any = []
const emptyString = ''
export function conformToMask(rawValue = emptyString, mask = emptyArray, config: any = {}) {
if (!isArray(mask)) {
// If someone passes a function as the mask property, we should call the
// function to get the mask array - Normally this is handled by the
// `createTextMaskInputElement:update` function - this allows mask functions
// to be used directly with `conformToMask`
if (typeof mask === strFunction) {
// call the mask function to get the mask array
mask = mask(rawValue, config)
// mask functions can setup caret traps to have some control over how the caret moves. We need to process
// the mask for any caret traps. `processCaretTraps` will remove the caret traps from the mask
mask = processCaretTraps(mask).maskWithoutCaretTraps
} else {
throw new Error(
'Text-mask:conformToMask; The mask property must be an array.'
)
}
}
// These configurations tell us how to conform the mask
const guide = config.guide || true;
const previousConformedValue = config.previousConformedValue || emptyString;
const placeholder = convertMaskToPlaceholder(mask, placeholderChar);
const currentCaretPosition = config.currentCaretPosition;
const keepCharPositions = config.keepCharPositions;
// The configs below indicate that the user wants the algorithm to work in *no guide* mode
const suppressGuide = guide === false && previousConformedValue !== undefined
// Calculate lengths once for performance
const rawValueLength = rawValue.length
const previousConformedValueLength = previousConformedValue.length
const placeholderLength = placeholder.length
const maskLength = mask.length
// This tells us the number of edited characters and the direction in which they were edited (+/-)
const editDistance = rawValueLength - previousConformedValueLength
// In *no guide* mode, we need to know if the user is trying to add a character or not
const isAddition = editDistance > 0
// Tells us the index of the first change. For (438) 394-4938 to (38) 394-4938, that would be 1
const indexOfFirstChange = currentCaretPosition + (isAddition ? -editDistance : 0)
// We're also gonna need the index of last change, which we can derive as follows...
const indexOfLastChange = indexOfFirstChange + Math.abs(editDistance)
// If `conformToMask` is configured to keep character positions, that is, for mask 111, previous value
// _2_ and raw value 3_2_, the new conformed value should be 32_, not 3_2 (default behavior). That's in the case of
// addition. And in the case of deletion, previous value _23, raw value _3, the new conformed string should be
// __3, not _3_ (default behavior)
//
// The next block of logic handles keeping character positions for the case of deletion. (Keeping
// character positions for the case of addition is further down since it is handled differently.)
// To do this, we want to compensate for all characters that were deleted
if (keepCharPositions === true && !isAddition) {
// We will be storing the new placeholder characters in this variable.
let compensatingPlaceholderChars = emptyString
// For every character that was deleted from a placeholder position, we add a placeholder char
for (let i = indexOfFirstChange; i < indexOfLastChange; i++) {
if (placeholder[i] === placeholderChar) {
compensatingPlaceholderChars += placeholderChar
}
}
// Now we trick our algorithm by modifying the raw value to make it contain additional placeholder characters
// That way when the we start laying the characters again on the mask, it will keep the non-deleted characters
// in their positions.
rawValue = (
rawValue.slice(0, indexOfFirstChange) +
compensatingPlaceholderChars +
rawValue.slice(indexOfFirstChange, rawValueLength)
)
}
// Convert `rawValue` string to an array, and mark characters based on whether they are newly added or have
// existed in the previous conformed value. Identifying new and old characters is needed for `conformToMask`
// to work if it is configured to keep character positions.
const rawValueArr = rawValue
.split(emptyString)
.map((char, i) => ({ char, isNew: i >= indexOfFirstChange && i < indexOfLastChange }))
// The loop below removes masking characters from user input. For example, for mask
// `00 (111)`, the placeholder would be `00 (___)`. If user input is `00 (234)`, the loop below
// would remove all characters but `234` from the `rawValueArr`. The rest of the algorithm
// then would lay `234` on top of the available placeholder positions in the mask.
for (let i = rawValueLength - 1; i >= 0; i--) {
const { char } = rawValueArr[i]
if (char !== placeholderChar) {
const shouldOffset = i >= indexOfFirstChange && previousConformedValueLength === maskLength
if (char === placeholder[(shouldOffset) ? i - editDistance : i]) {
rawValueArr.splice(i, 1)
}
}
}
// This is the variable that we will be filling with characters as we figure them out
// in the algorithm below
let conformedValue = emptyString
let someCharsRejected = false
// Ok, so first we loop through the placeholder looking for placeholder characters to fill up.
placeholderLoop: for (let i = 0; i < placeholderLength; i++) {
const charInPlaceholder = placeholder[i]
// We see one. Let's find out what we can put in it.
if (charInPlaceholder === placeholderChar) {
// But before that, do we actually have any user characters that need a place?
if (rawValueArr.length > 0) {
// We will keep chipping away at user input until either we run out of characters
// or we find at least one character that we can map.
while (rawValueArr.length > 0) {
// Let's retrieve the first user character in the queue of characters we have left
const { char: rawValueChar, isNew } = rawValueArr.shift()
// If the character we got from the user input is a placeholder character (which happens
// regularly because user input could be something like (540) 90_-____, which includes
// a bunch of `_` which are placeholder characters) and we are not in *no guide* mode,
// then we map this placeholder character to the current spot in the placeholder
if (rawValueChar === placeholderChar && suppressGuide !== true) {
conformedValue += placeholderChar
// And we go to find the next placeholder character that needs filling
continue placeholderLoop
// Else if, the character we got from the user input is not a placeholder, let's see
// if the current position in the mask can accept it.
} else if (mask[i].test(rawValueChar)) {
// we map the character differently based on whether we are keeping character positions or not.
// If any of the conditions below are met, we simply map the raw value character to the
// placeholder position.
if (
keepCharPositions !== true ||
isNew === false ||
previousConformedValue === emptyString ||
guide === false ||
!isAddition
) {
conformedValue += rawValueChar
} else {
// We enter this block of code if we are trying to keep character positions and none of the conditions
// above is met. In this case, we need to see if there's an available spot for the raw value character
// to be mapped to. If we couldn't find a spot, we will discard the character.
//
// For example, for mask `1111`, previous conformed value `_2__`, raw value `942_2__`. We can map the
// `9`, to the first available placeholder position, but then, there are no more spots available for the
// `4` and `2`. So, we discard them and end up with a conformed value of `92__`.
const rawValueArrLength = rawValueArr.length
let indexOfNextAvailablePlaceholderChar = null
// Let's loop through the remaining raw value characters. We are looking for either a suitable spot, ie,
// a placeholder character or a non-suitable spot, ie, a non-placeholder character that is not new.
// If we see a suitable spot first, we store its position and exit the loop. If we see a non-suitable
// spot first, we exit the loop and our `indexOfNextAvailablePlaceholderChar` will stay as `null`.
for (let i = 0; i < rawValueArrLength; i++) {
const charData = rawValueArr[i]
if (charData.char !== placeholderChar && charData.isNew === false) {
break
}
if (charData.char === placeholderChar) {
indexOfNextAvailablePlaceholderChar = i
break
}
}
// If `indexOfNextAvailablePlaceholderChar` is not `null`, that means the character is not blocked.
// We can map it. And to keep the character positions, we remove the placeholder character
// from the remaining characters
if (indexOfNextAvailablePlaceholderChar !== null) {
conformedValue += rawValueChar
rawValueArr.splice(indexOfNextAvailablePlaceholderChar, 1)
// If `indexOfNextAvailablePlaceholderChar` is `null`, that means the character is blocked. We have to
// discard it.
} else {
i--
}
}
// Since we've mapped this placeholder position. We move on to the next one.
continue placeholderLoop
} else {
someCharsRejected = true
}
}
}
// We reach this point when we've mapped all the user input characters to placeholder
// positions in the mask. In *guide* mode, we append the left over characters in the
// placeholder to the `conformedString`, but in *no guide* mode, we don't wanna do that.
//
// That is, for mask `(111)` and user input `2`, we want to return `(2`, not `(2__)`.
if (suppressGuide === false) {
conformedValue += placeholder.substr(i, placeholderLength)
}
// And we break
break
// Else, the charInPlaceholder is not a placeholderChar. That is, we cannot fill it
// with user input. So we just map it to the final output
} else {
conformedValue += charInPlaceholder
}
}
// The following logic is needed to deal with the case of deletion in *no guide* mode.
//
// Consider the silly mask `(111) /// 1`. What if user tries to delete the last placeholder
// position? Something like `(589) /// `. We want to conform that to `(589`. Not `(589) /// `.
// That's why the logic below finds the last filled placeholder character, and removes everything
// from that point on.
if (suppressGuide && isAddition === false) {
let indexOfLastFilledPlaceholderChar = null
// Find the last filled placeholder position and substring from there
for (let i = 0; i < conformedValue.length; i++) {
if (placeholder[i] === placeholderChar) {
indexOfLastFilledPlaceholderChar = i
}
}
if (indexOfLastFilledPlaceholderChar !== null) {
// We substring from the beginning until the position after the last filled placeholder char.
conformedValue = conformedValue.substr(0, indexOfLastFilledPlaceholderChar + 1)
} else {
// If we couldn't find `indexOfLastFilledPlaceholderChar` that means the user deleted
// the first character in the mask. So we return an empty string.
conformedValue = emptyString
}
}
return { conformedValue, meta: { someCharsRejected } }
}
export function convertMaskToPlaceholder(mask = emptyArray, placeholderChar = defaultPlaceholderChar) {
if (!isArray(mask)) {
throw new Error(
'Text-mask:convertMaskToPlaceholder; The mask property must be an array.'
)
}
if (mask.indexOf(placeholderChar) !== -1) {
throw new Error(
'Placeholder character must not be used as part of the mask. Please specify a character ' +
'that is not present in your mask as your placeholder character.\n\n' +
`The placeholder character that was received is: ${JSON.stringify(placeholderChar)}\n\n` +
`The mask that was received is: ${JSON.stringify(mask)}`
)
}
return mask.map((char) => {
return (char instanceof RegExp) ? placeholderChar : char
}).join('')
}

@@ -1,103 +0,1 @@

import { IEMASKS } from './inscricaoestadual';
import createNumberMask from 'text-mask-addons/dist/createNumberMask'
export const ESTADOS_SIGLA = ['ac', 'al', 'am', 'ap', 'ba', 'ce', 'df', 'es', 'go', 'ma',
'mg', 'ms', 'mt', 'pa', 'pb', 'pe', 'pi', 'pr', 'rj', 'rn', 'ro', 'rr', 'rs',
'sc', 'se', 'sp', 'to'
];
export const MASKS = {
cpf: {
text: '000.000.000-00',
textMask: [/\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '-', /\d/, /\d/]
},
cnpj: {
text: '00.000.000/0000-00',
textMask: [/\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '/', /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/]
},
rg: {
text: 'AA-00.000.000',
textMask: [/[A-Za-z]/, /[A-Za-z]/, '-', /\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/]
},
telefone: {
text: '(00) 0000-0000',
textMask: ['(', /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/],
textMaskFunction: function mask(userInput) {
const numbers = userInput.match(/\d/g);
let numberLength = 0;
if (numbers) {
numberLength = numbers.join('').length;
}
if (!userInput || numberLength > 10) {
return ['(', /[1-9]/, /\d/, ')', ' ', /[1-9]/, /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/];
} else {
return ['(', /[1-9]/, /\d/, ')', ' ', /[1-9]/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/];
}
}
},
celular: {
text: '(00) 00000-0000',
textMask: ['(', /[1-9]/, /\d/, ')', ' ', /[5-9]/, /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/],
},
cep: {
text: '00.000-000',
textMask: [/\d/, /\d/, '.', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/]
},
inscricaoestadual: IEMASKS,
time: {
text: '00:00',
textMask: [/\d/, /\d/, ':', /\d/, /\d/]
},
currency: {
text: '0.000,00',
textMask: createNumberMask({
decimalLimit: 2,
thousandsSeparatorSymbol: '.',
decimalSymbol: ',',
allowDecimal: true,
integerLimit: 15,
prefix: 'R$ ',
suffix: ''
})
},
percentage: {
text: '00,00%',
textMask: createNumberMask({
decimalLimit: 2,
thousandsSeparatorSymbol: '.',
decimalSymbol: ',',
allowDecimal: true,
integerLimit: 15,
prefix: '',
suffix: '%'
})
},
placa: {
text: 'AAA-0000',
textMask: [/[A-Za-z]/, /[A-Za-z]/, /[A-Za-z]/, '-', /\d/, /\d/, /\d/, /\d/]
},
titulo: {
text: '0000.0000.0000',
textMask: [/\d/, /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, /\d/]
},
processo: {
text: '0000000-00.0000.AAA.0000',
textMask: [/\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, '.', /\d/, /\d/, /\d/, /\d/, '.', /[A-Za-z]/, /[A-Za-z]/, /[A-Za-z]/, '.', /\d/, /\d/, /\d/, /\d/]
},
renavam: {
textMaskFunction: function mask(userInput) {
const numbers = userInput.match(/\d/g);
let numberLength = 0;
if (numbers) {
numberLength = numbers.join('').length;
}
if (!userInput || numberLength < 9) {
return [/\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/];
} else {
return [/\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/];
}
}
}
}
export function isPresent(obj: any): boolean {

@@ -107,277 +5,2 @@ return obj !== undefined && obj !== null;

/**
* FROM TEXT-MASK
*/
export const placeholderChar = '_'
export const strFunction = 'function'
const defaultPlaceholderChar = placeholderChar;
const emptyArray: any = []
const emptyString = ''
export function conformToMask(rawValue = emptyString, mask = emptyArray, config: any = {}) {
if (!isArray(mask)) {
// If someone passes a function as the mask property, we should call the
// function to get the mask array - Normally this is handled by the
// `createTextMaskInputElement:update` function - this allows mask functions
// to be used directly with `conformToMask`
if (typeof mask === strFunction) {
// call the mask function to get the mask array
mask = mask(rawValue, config)
// mask functions can setup caret traps to have some control over how the caret moves. We need to process
// the mask for any caret traps. `processCaretTraps` will remove the caret traps from the mask
mask = processCaretTraps(mask).maskWithoutCaretTraps
} else {
throw new Error(
'Text-mask:conformToMask; The mask property must be an array.'
)
}
}
// These configurations tell us how to conform the mask
const guide = config.guide || true;
const previousConformedValue = config.previousConformedValue || emptyString;
const placeholder = convertMaskToPlaceholder(mask, placeholderChar);
const currentCaretPosition = config.currentCaretPosition;
const keepCharPositions = config.keepCharPositions;
// The configs below indicate that the user wants the algorithm to work in *no guide* mode
const suppressGuide = guide === false && previousConformedValue !== undefined
// Calculate lengths once for performance
const rawValueLength = rawValue.length
const previousConformedValueLength = previousConformedValue.length
const placeholderLength = placeholder.length
const maskLength = mask.length
// This tells us the number of edited characters and the direction in which they were edited (+/-)
const editDistance = rawValueLength - previousConformedValueLength
// In *no guide* mode, we need to know if the user is trying to add a character or not
const isAddition = editDistance > 0
// Tells us the index of the first change. For (438) 394-4938 to (38) 394-4938, that would be 1
const indexOfFirstChange = currentCaretPosition + (isAddition ? -editDistance : 0)
// We're also gonna need the index of last change, which we can derive as follows...
const indexOfLastChange = indexOfFirstChange + Math.abs(editDistance)
// If `conformToMask` is configured to keep character positions, that is, for mask 111, previous value
// _2_ and raw value 3_2_, the new conformed value should be 32_, not 3_2 (default behavior). That's in the case of
// addition. And in the case of deletion, previous value _23, raw value _3, the new conformed string should be
// __3, not _3_ (default behavior)
//
// The next block of logic handles keeping character positions for the case of deletion. (Keeping
// character positions for the case of addition is further down since it is handled differently.)
// To do this, we want to compensate for all characters that were deleted
if (keepCharPositions === true && !isAddition) {
// We will be storing the new placeholder characters in this variable.
let compensatingPlaceholderChars = emptyString
// For every character that was deleted from a placeholder position, we add a placeholder char
for (let i = indexOfFirstChange; i < indexOfLastChange; i++) {
if (placeholder[i] === placeholderChar) {
compensatingPlaceholderChars += placeholderChar
}
}
// Now we trick our algorithm by modifying the raw value to make it contain additional placeholder characters
// That way when the we start laying the characters again on the mask, it will keep the non-deleted characters
// in their positions.
rawValue = (
rawValue.slice(0, indexOfFirstChange) +
compensatingPlaceholderChars +
rawValue.slice(indexOfFirstChange, rawValueLength)
)
}
// Convert `rawValue` string to an array, and mark characters based on whether they are newly added or have
// existed in the previous conformed value. Identifying new and old characters is needed for `conformToMask`
// to work if it is configured to keep character positions.
const rawValueArr = rawValue
.split(emptyString)
.map((char, i) => ({ char, isNew: i >= indexOfFirstChange && i < indexOfLastChange }))
// The loop below removes masking characters from user input. For example, for mask
// `00 (111)`, the placeholder would be `00 (___)`. If user input is `00 (234)`, the loop below
// would remove all characters but `234` from the `rawValueArr`. The rest of the algorithm
// then would lay `234` on top of the available placeholder positions in the mask.
for (let i = rawValueLength - 1; i >= 0; i--) {
const { char } = rawValueArr[i]
if (char !== placeholderChar) {
const shouldOffset = i >= indexOfFirstChange && previousConformedValueLength === maskLength
if (char === placeholder[(shouldOffset) ? i - editDistance : i]) {
rawValueArr.splice(i, 1)
}
}
}
// This is the variable that we will be filling with characters as we figure them out
// in the algorithm below
let conformedValue = emptyString
let someCharsRejected = false
// Ok, so first we loop through the placeholder looking for placeholder characters to fill up.
placeholderLoop: for (let i = 0; i < placeholderLength; i++) {
const charInPlaceholder = placeholder[i]
// We see one. Let's find out what we can put in it.
if (charInPlaceholder === placeholderChar) {
// But before that, do we actually have any user characters that need a place?
if (rawValueArr.length > 0) {
// We will keep chipping away at user input until either we run out of characters
// or we find at least one character that we can map.
while (rawValueArr.length > 0) {
// Let's retrieve the first user character in the queue of characters we have left
const { char: rawValueChar, isNew } = rawValueArr.shift()
// If the character we got from the user input is a placeholder character (which happens
// regularly because user input could be something like (540) 90_-____, which includes
// a bunch of `_` which are placeholder characters) and we are not in *no guide* mode,
// then we map this placeholder character to the current spot in the placeholder
if (rawValueChar === placeholderChar && suppressGuide !== true) {
conformedValue += placeholderChar
// And we go to find the next placeholder character that needs filling
continue placeholderLoop
// Else if, the character we got from the user input is not a placeholder, let's see
// if the current position in the mask can accept it.
} else if (mask[i].test(rawValueChar)) {
// we map the character differently based on whether we are keeping character positions or not.
// If any of the conditions below are met, we simply map the raw value character to the
// placeholder position.
if (
keepCharPositions !== true ||
isNew === false ||
previousConformedValue === emptyString ||
guide === false ||
!isAddition
) {
conformedValue += rawValueChar
} else {
// We enter this block of code if we are trying to keep character positions and none of the conditions
// above is met. In this case, we need to see if there's an available spot for the raw value character
// to be mapped to. If we couldn't find a spot, we will discard the character.
//
// For example, for mask `1111`, previous conformed value `_2__`, raw value `942_2__`. We can map the
// `9`, to the first available placeholder position, but then, there are no more spots available for the
// `4` and `2`. So, we discard them and end up with a conformed value of `92__`.
const rawValueArrLength = rawValueArr.length
let indexOfNextAvailablePlaceholderChar = null
// Let's loop through the remaining raw value characters. We are looking for either a suitable spot, ie,
// a placeholder character or a non-suitable spot, ie, a non-placeholder character that is not new.
// If we see a suitable spot first, we store its position and exit the loop. If we see a non-suitable
// spot first, we exit the loop and our `indexOfNextAvailablePlaceholderChar` will stay as `null`.
for (let i = 0; i < rawValueArrLength; i++) {
const charData = rawValueArr[i]
if (charData.char !== placeholderChar && charData.isNew === false) {
break
}
if (charData.char === placeholderChar) {
indexOfNextAvailablePlaceholderChar = i
break
}
}
// If `indexOfNextAvailablePlaceholderChar` is not `null`, that means the character is not blocked.
// We can map it. And to keep the character positions, we remove the placeholder character
// from the remaining characters
if (indexOfNextAvailablePlaceholderChar !== null) {
conformedValue += rawValueChar
rawValueArr.splice(indexOfNextAvailablePlaceholderChar, 1)
// If `indexOfNextAvailablePlaceholderChar` is `null`, that means the character is blocked. We have to
// discard it.
} else {
i--
}
}
// Since we've mapped this placeholder position. We move on to the next one.
continue placeholderLoop
} else {
someCharsRejected = true
}
}
}
// We reach this point when we've mapped all the user input characters to placeholder
// positions in the mask. In *guide* mode, we append the left over characters in the
// placeholder to the `conformedString`, but in *no guide* mode, we don't wanna do that.
//
// That is, for mask `(111)` and user input `2`, we want to return `(2`, not `(2__)`.
if (suppressGuide === false) {
conformedValue += placeholder.substr(i, placeholderLength)
}
// And we break
break
// Else, the charInPlaceholder is not a placeholderChar. That is, we cannot fill it
// with user input. So we just map it to the final output
} else {
conformedValue += charInPlaceholder
}
}
// The following logic is needed to deal with the case of deletion in *no guide* mode.
//
// Consider the silly mask `(111) /// 1`. What if user tries to delete the last placeholder
// position? Something like `(589) /// `. We want to conform that to `(589`. Not `(589) /// `.
// That's why the logic below finds the last filled placeholder character, and removes everything
// from that point on.
if (suppressGuide && isAddition === false) {
let indexOfLastFilledPlaceholderChar = null
// Find the last filled placeholder position and substring from there
for (let i = 0; i < conformedValue.length; i++) {
if (placeholder[i] === placeholderChar) {
indexOfLastFilledPlaceholderChar = i
}
}
if (indexOfLastFilledPlaceholderChar !== null) {
// We substring from the beginning until the position after the last filled placeholder char.
conformedValue = conformedValue.substr(0, indexOfLastFilledPlaceholderChar + 1)
} else {
// If we couldn't find `indexOfLastFilledPlaceholderChar` that means the user deleted
// the first character in the mask. So we return an empty string.
conformedValue = emptyString
}
}
return { conformedValue, meta: { someCharsRejected } }
}
export function convertMaskToPlaceholder(mask = emptyArray, placeholderChar = defaultPlaceholderChar) {
if (!isArray(mask)) {
throw new Error(
'Text-mask:convertMaskToPlaceholder; The mask property must be an array.'
)
}
if (mask.indexOf(placeholderChar) !== -1) {
throw new Error(
'Placeholder character must not be used as part of the mask. Please specify a character ' +
'that is not present in your mask as your placeholder character.\n\n' +
`The placeholder character that was received is: ${JSON.stringify(placeholderChar)}\n\n` +
`The mask that was received is: ${JSON.stringify(mask)}`
)
}
return mask.map((char) => {
return (char instanceof RegExp) ? placeholderChar : char
}).join('')
}
export function isArray(value) {

@@ -411,2 +34,16 @@ return (Array.isArray && Array.isArray(value)) || value instanceof Array

return { maskWithoutCaretTraps: mask, indexes }
}
export const modulo11 = (string, size, mod)=>{
let soma = 0;
for (let i = 1; i <= size; i++) {
// tslint:disable-next-line:radix
soma = soma + parseInt(string.substring(i - 1, i)) * (mod - i);
}
let resto = (soma * 10) % 11;
if ((resto === 10) || (resto === 11)) {
resto = 0;
}
return resto;
}

@@ -0,1 +1,2 @@

import { modulo11 } from "./utils";

@@ -92,5 +93,2 @@ // http://www.geradorcnpj.com/javascript-validar-cnpj.htm

strCPF = strCPF.replace(/[^\d]+/g, '');
let soma;
let resto;
soma = 0;
if (strCPF === '00000000000') {

@@ -100,26 +98,7 @@ return false;

for (let i = 1; i <= 9; i++) {
// tslint:disable-next-line:radix
soma = soma + parseInt(strCPF.substring(i - 1, i)) * (11 - i);
}
resto = (soma * 10) % 11;
const restos = [
modulo11(strCPF, 9, 11),
modulo11(strCPF, 10, 12)
];
if ((resto === 10) || (resto === 11)) {
resto = 0;
}
const restos = [];
restos.push(resto);
soma = 0;
for (let i = 1; i <= 10; i++) {
soma = soma + parseInt(strCPF.substring(i - 1, i), 10) * (12 - i);
}
resto = (soma * 10) % 11;
if ((resto === 10) || (resto === 11)) {
resto = 0;
}
restos.push(resto);
return restos;

@@ -194,7 +173,2 @@ }

}
// const exp = /\(\d{2}\)\ \d{4}\-\d{4}/;
// const exp5 = /\(\d{2}\)\ \d{5}\-\d{4}/;
// if (!exp.test(tel) && !exp5.test(tel)) {
// return false;
// }
return true;

@@ -205,5 +179,5 @@ }

export function validate_celular(cel) {
const celClean = cel.replace(/[^\d]+/g, '');
cel = cel.replace(/_/g, '');
if (!(celClean.length === 10 || celClean.length === 11)) {
let celClean = cel.replace(/[^\d]+/g, '');
celClean = celClean.replace(/_/g, '');
if (celClean.length !== 11) {
return false;

@@ -245,14 +219,3 @@ }

export function validate_placa(placa) {
const placaClean = placa.replace(/-/g, '');
const exp = /[A-Za-z]{3}\-\d{4}/;
const expClean = /[A-Za-z]{3}\d{4}/;
// const letters = placa.substr(0, 3).toUpperCase();
if (!exp.test(placa) && !expClean.test(placaClean)) {
return false;
}
return true;
}
export function validate_titulo(titulo) {

@@ -339,6 +302,2 @@ const tituloClean = titulo.replace(/\./g, '');

renavamClean = renavamClean.replace(/\-/g, '');
// const expClean = /\d{10}\d{4}\d{4}/;
// if (!exp.test(renavamClean) && !expClean.test(renavamClean)) {
// return false;
// }
const dv = create_renavam(renavam);

@@ -356,6 +315,6 @@ const tam = renavam.length;

let dig1 = 0;
const tam = renavam.length;
renavam = renavam.substr(0, tam - 2);
renavam = '000000000000' + renavam;
renavam = renavam.substr(renavam.length - 11, renavam.length - 1);
while (renavam.length < 11) {
renavam = '0' + renavam;
}
dig1 = (renavam.charCodeAt(0) - 48) * 3 + (renavam.charCodeAt(1) - 48) * 2 + (renavam.charCodeAt(2) - 48) * 9 + (renavam.charCodeAt(3) - 48) * 8 +

@@ -362,0 +321,0 @@ (renavam.charCodeAt(4) - 48) * 7 + (renavam.charCodeAt(5) - 48) * 6 + (renavam.charCodeAt(6) - 48) * 5 +

@@ -46,3 +46,2 @@ import { fakerBr, validateBr } from '../index';

const celular = fakerBr.celular();
console.log(celular)
expect(validateBr.celular(celular)).to.be.true;

@@ -49,0 +48,0 @@ });

@@ -15,2 +15,4 @@ import { validateBr } from '../index';

expect(validateBr.cpf('127.529.875-36')).to.be.true;
expect(validateBr.cpf('127.529.875-46')).to.be.false;
expect(validateBr.cpf('127.529.875-37')).to.be.false;
});

@@ -25,4 +27,13 @@

it('PLACA', () => {
expect(validateBr.placa('ABC1234')).to.be.true;
expect(validateBr.placa('SAW0002')).to.be.false;
});
it('RENAVAM', () => {
expect(validateBr.renavam('72176426415')).to.be.true;
expect(validateBr.renavam('72176426415')).to.be.true;
});
it('Telefone', () => {
expect(validateBr.telefone('31 999876767')).to.be.true;
expect(validateBr.telefone('31 99876767')).to.be.true;

@@ -34,2 +45,10 @@ expect(validateBr.telefone('(90) 1057-1600')).to.be.true;

it('Celular', () => {
// expect(validateBr.celular('31 999876767')).to.be.true;
expect(validateBr.celular('31 99876767')).to.be.false;
// expect(validateBr.celular('(90) 1057-1600')).to.be.true;
// expect(validateBr.celular('(90) 00057-1600')).to.be.false;
});
it('TITULO', () => {

@@ -56,5 +75,6 @@ expect(validateBr.titulo('6490.8084.4421')).to.be.true;

expect(validateBr.telefone('1234')).to.be.false;
expect(validateBr.celular('1234')).to.be.false;
expect(validateBr.time('1234')).to.be.false;
expect(validateBr.titulo('1234')).to.be.false;
});
});
});

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc