Field CPF, CNPJ and Other Document - jQuery validation

Asked

Viewed 910 times

-2

I have a field where you can write the CPF, CNPJ and Other Document. The field is no mask, while the "Other Document" can be any number or letter.

How can I make these validations in jQuery? Check if the user typed without mask or mask and/or if it is a document.

  • 1

    In that reply has an example of how to know if was inserted the CPF or CNPJ. Just adapt for Javascript.

3 answers

2

It seems to me from your description that any string that contains numbers or letters is valid. In this case just a simple match:

var valido = this.value.match(/^[\d\w]+$/);

Example:

var input = document.querySelector('input');
var res = document.getElementById('res');
input.addEventListener('keyup', function() {
    var valido = this.value.match(/^[\d\w]+$/);
    res.innerHTML = valido ? 'valido' : 'invalido';
});
<input type="text" placeholder="escreve algo aqui...">
<div id="res"></div>

jsFiddle: https://jsfiddle.net/g5o1gp45/

  • very good @Sergio, how can I remove all the special characters, using the same Regex that you did when it changes the field value, ie "onchange"

  • @Can Furlan give an example of what should be modified? You mean taking away the - between the numbers?

  • yes, the " . " tbm

  • @Furlan is what you’re looking for? -> https://jsfiddle.net/g5o1gp45/1/

  • not exactly, I need that in the event "onchange" it removes all the special characters, allowing only letters and numbers

  • 1

    @Furlan :) the change in this case is minimal, and I think you know how to do :) -> https://jsfiddle.net/g5o1gp45/2/

Show 1 more comment

1


You will only be able to do this when the courses leave the field, before that there is no way you can predict what will be inserted: CPF, CNPJ or Other Document.

I’d go like this: In the onblur - field output - would take the content of the text, filter only the numbers and if it has 11 digits it would format as CPF, if it has 14 as CNPJ, otherwise it would not format.

  • Okay, thanks for responding

  • 1

    @Furlan, if satisfied, please mark as answer to your question. Thank you!

1

There is a plugin for jQuery that is very well known called jQuery Validation Plugin which greatly facilitates validation processes using jQuery. You can take a look at their documentation to learn how to use, here the link.

Browser other questions tagged

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