How to create Pattern (input mask) with jQuery Validation Plugin?

Asked

Viewed 1,183 times

1

I need to create a input mask (Pattern) for the type CPF 000.000.000-00 and to CNPJ 00.000.000/0000-00 through the plugin jQuery Validation. What would be the regex to be creating this validation?

Note: CPF and CNPJ will be two different inputs.

Grateful.

  • Do you want to take the test to know if the CPF and CNPJ is valid? or just check if this format? if you want to see if it is valid, it will not be possible, because it follows a calculation algorithm by type checker. It would have to be a function.

  • Hello William, I just want to check if this format.

1 answer

2

For this you can use the jQuery Mask.

$(document).ready(function(){
  $('.cpf').mask('000.000.000-00');
  $('.cnpj').mask('00.000.000/0000-00');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://igorescobar.github.io/jQuery-Mask-Plugin/js/jquery.mask.min.js"></script>

CPF :<input type="text" class="cpf">
<br/>
CNPJ :<input type="text" class="cnpj">

Note

  • Remembering that so it does not check if it is a valid content, just put in this format.

Edit

Regexs to validate CPF and CNPJ could be

  • CPF : \d{3}\.\d{3}\.\d{3}-\d{2}
  • CNPJ : \d\d\.\d{3}\.\d{3}-\d{4}-\d\d

See on REGEX101.

  • Hello William, actually I need this validation through this plugin (jQuery Validation) even, because I got a Wordpress Theme and I’m having to perform some implementations, all validations and masks of the inputs of the forms are made through this plugin. I know more or less above how to create the function for this, I just really need the regex for CPF and CNPJ fields.

  • @Rodrigofontes edited.

Browser other questions tagged

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