I believe the limit is 13 characters in the mask, because of the format 000 000 000 0
, then start applying maxlength="13"
to prevent the user from typing too many things.
In the example I used 2 regex:
/^(\d{3})(\d{3})(\d{3})(\d)+$/ <-- para extrair os numeros
/^(\d{3}) (\d{3}) (\d{3})(\d)+$/ <-- para validar após aplicar a mascara
Regex:
function MascaraFormato(campo)
{
if (!campo) return;
//extrai os numeros
var formato = /^(\d{3})(\d{3})(\d{3})(\d)+$/;
//valida o formato final
var valido = /^(\d{3}) (\d{3}) (\d{3}) (\d)+$/;
var timer, // Para evitar multiplas execuções
executando; // Para preveinir o ".value = " disparar o evento
function mascara()
{
if (executando) return;
//Remove os numeros
var matricula = campo.value.replace(/\D/g, "");
//Extrai os numeros
matricula = matricula.replace(formato, "$1 $2 $3 $4");
//Bloqueia o ".value=" para evitar conflitos
executando = true;
//Testa se o formato foi extraido
if (valido.test(matricula)) {
campo.value = matricula;
campo.classList.remove("invalido");
//se não validar então limpa o campo
} else {
campo.value = ""; //Apaga o campo
campo.classList.add("invalido");
}
// libera para voltar a aplicar a mascar, acaso ocorra outra alteração
executando = false;
}
mascara(); //Executa a mascara quando a "página carrega"
campo.addEventListener('input', function () {
// Previne multiplas execuções
if (timer) clearTimeout(timer);
timer = setTimeout(mascara, 500);
});
}
//Aplica a um campo
MascaraFormato(document.querySelector('#matricula'));
//Aplica a outro campo
MascaraFormato(document.querySelector('#outro'));
<input id="matricula" maxlength="13">
<input id="outro" maxlength="13">
A simpler way would be to use .match
to divide the string from 3 to 3, then with substring
remove what is not important and to validate the format just check if the string size is the same as the maxlength="13"
, or if it is smaller/different 13 means that the entered value is not valid
It took a regex only to split the string, but overall it is simpler, example:
function MascaraFormato(campo)
{
if (!campo) return;
var maxLength = parseInt( campo.getAttribute("maxlength") );
var timer, executando; // Para preveinir o ".value = " disparar o evento
function mascara()
{
if (executando) return;
//Remove os numeros
var matricula = campo.value.replace(/\D/g, "");
//Divide a string de 3 em 3 (array)
matricula = matricula.match(/.{1,3}/g);
if (matricula) {
//com .join junta novamente aplicando espaços
matricula = matricula.join(" ");
//Limita a string ao tamanho de 13 caracteres, o mesmo do maxlength
matricula = matricula.substring(0, maxLength);
//Bloqueia o ".value=" para evitar conflitos
executando = true;
//Testa se o formato foi extraido, deve ter o tamanho exato
if (matricula.length == maxLength) {
campo.value = matricula;
campo.classList.remove("invalido");
executando = false;
return; //Para a função neste ponto
}
}
campo.value = ""; //Apaga o campo se for invalid
campo.classList.add("invalido");
executando = false;
}
mascara(); //Executa a mascara quando a "página carrega"
campo.addEventListener('input', function () {
// Previne multiplas execuções
if (timer) clearTimeout(timer);
timer = setTimeout(mascara, 500);
});
}
//Aplica a um campo
MascaraFormato(document.querySelector('#matricula'));
//Aplica a outro campo
MascaraFormato(document.querySelector('#outro'));
<input id="matricula" maxlength="13">
<input id="outro" maxlength="13">
If you only need to change the format, it is defined by the regular expression in the code. I therefore recommend that you study regular expressions, understand what has been done and see how to set the new standard.
– Woss
I’m not getting through
– Snoopy12
More details, please. What didn’t you get? Read about regular expressions? Tried to understand what was done? Tip: you can use https://regex101.com to test your expressions.
– Woss
I am trying to format this "replace(/( d{4,5})( d{1})$/,"$1-$2");" in this 000-000-000 0
– Snoopy12
Okay, but what was your attempt? Your last comment was basically a summary of what is in the question and did not add details to the problem. Again, do you know regular expression? If not, have you studied them? If you are trying, put your attempts and describe the result obtained, whether it is an error or just an unexpected return. Basically show what was your effort in solving the problem.
– Woss
replace(/(\d{3})$(\d{3})$(\d{3})$/,"$1-$2");
– Snoopy12