Validate any input at the same time

Asked

Viewed 58 times

-1

I’m doing a live validation of the CPF field entry, but I don’t want you to let letters in and do a "data mask"

cpf[0].onkeypress = function (e) {
var key = e.key
for(let i = 0 ; i <cpf[0].value.length ;i++) {
    if(cpf[0].value[i]==1 ||cpf[0].value[i]==2 ||cpf[0].value[i]==3 ||cpf[0].value[i]==4 ||cpf[0].value[i]==5 ||
        cpf[0].value[i]==6 ||cpf[0].value[i]==7 ||cpf[0].value[i]==8 ||cpf[0].value[i]==9 ||cpf[0].value[i]==10 ||
         cpf[0].value[i]=='.' || cpf[0].value[i]=='-') {

        } else {
            cpf[0].value="";
        }
}
if(key==1 ||key==2 ||key==3 ||key==4 ||key==5 ||
    key==6 ||key==7 ||key==8 ||key==9 ||key==10 ) {
    if(cpf[0].value.length==3){
        cpf[0].value+='.';
    } else if(cpf[0].value.length==7) {
        cpf[0].value+='.';
    } else if(cpf[0].value.length==11) {
        cpf[0].value+='-';
    }
} else {
    cpf[0].value="";
}

But it turns out that when the person type the letter he clears the entire field of the CPF and leaves the letter that the person typed, how can I fix it?

  • Hello. Already tried using onChange instead of onkeypress?

2 answers

0

If you just want to reset your input numbers, change its type.

<input type="number" name="cpf">

This way your input can only receive numbers.

  • Yes, but I wanted to do something more professional by putting a data mask

0

Another option would be to use a Jquery plugin to accept only numbers and insert dots and dash. Here’s an example:

https://igorescobar.github.io/jQuery-Mask-Plugin/

After downloading the plugin and copying to the same folder where your HTML is, you can use it as follows:

<html>
<head>
<title>Mascara de CPF</title>
<script
  src="https://code.jquery.com/jquery-3.4.1.js"
  integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
  crossorigin="anonymous"></script>
<script
  src="jQuery-Mask-Plugin-master/jQuery-Mask-Plugin-master/src/jquery.mask.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $('#CPF').mask('000.000.000-00', {reverse: true});
});
</script>  
<body>  
	<form>
		<label>CPF</label>
		<input type="text" name="CPF" id="CPF">
	</form>
</body>

  • While this link may answer the question, it is best to include the essential parts of the answer here and provide the link for reference. Replies per link only can be invalidated if the page with the link is changed. - Of Revision

  • Thanks for letting me know. I’ve already added an example of how to use

  • Thank you very much for the answer, I will test here

Browser other questions tagged

You are not signed in. Login or sign up in order to post.