You can use the plugin JQuery Inputmask. With it you can define the data format of a input.
To define the format of the CPF, just use the following code jQuery:
$("#frmCpf").inputmask({
mask: "999.999.999-99"
});
Each 9 indicates that in this position only values in the range [0, 9]. If you don’t want the . and the -, just remove them from the mask.
Another way to use the InputMask is direct in html, with the attribute data-inputmask.
<input type="text" id="frmNumero" name="frmNumero" placeholder="Somente números" data-inputmask="'mask': '9', 'repeat': 10, 'greedy' : false"/>
Then just call $("#frmNumero").inputmask(); in the JavaScript.
The estate repeat indicates how many times the mask will repeat. In the case of input above, we can insert values in the range [0, 9] a maximum of 10 times. Already the property greedy: false causes the plugin display the smallest mask he can.
It is important that you read on documentation if creating new masks.
Follow an example by running:
$(function(){
$("#frmCpf").inputmask({
mask: "999.999.999-99"
});
$("#frmNumero").inputmask();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://rawgit.com/RobinHerbots/jquery.inputmask/3.x/dist/jquery.inputmask.bundle.js"></script>
<input type="text" id="frmCpf" name="frmCpf" placeholder="Somente números"/>
<input type="text" id="frmNumero" name="frmNumero" placeholder="Somente números" data-inputmask="'mask': '9', 'repeat': 10, 'greedy' : false"/>
If you’re not using JQuery:
You can use the Vanillamasker.
To set the CPF format, just use maskPattern, as in the following code:
VMasker(document.getElementById("frmCpf")).maskPattern("999.999.999-99");
The mask works in a similar way to what I said to the InputMask.
To indicate that a field is only numerical, just use the method maskNumber, as in the following code:
VMasker(document.getElementById("frmNumero")).maskNumber();
Follow an example using the VanillaMasker:
VMasker(document.getElementById("frmCpf")).maskPattern("999.999.999-99");
VMasker(document.getElementById("frmNumero")).maskNumber();
<script src="//unpkg.com/[email protected]/build/vanilla-masker.min.js"></script>
<input type="text" id="frmCpf" name="frmCpf" placeholder="Somente números"/>
<input type="text" id="frmNumero" name="frmNumero" placeholder="Somente números" data-inputmask="'mask': '9', 'repeat': 10, 'greedy' : false"/>
Is he using jQuery?
– LeAndrade
Thanks for remembering. I added a library without
jQuery.– Mauro Roberto