Check if CPF already exists with Jquery Validate

Asked

Viewed 664 times

1

I am validating some fields of an application form that was made in Ruby on Rails. In this application has some query endpoint, where it returns a json, if the CPF exists it returns this data:

{
  "existe": true,
  "user": {
  "name": "Operador 2",
  "cpf": "606.304.220-29"
  }
}

And if it doesn’t exist it returns

{  
   "existe":false
}

The URL to query the CPF is the following way: http://localhost:3000/api/findUserByCpf? Cpf=606.304.220-28

And the js code of Jquery Validation, he’s returning the message on the console, but doesn’t help the countryside, making the field valid or invalid.

$(".validationNomeOperador").validate({
rules: {
    'cpf': {
        required: true,
        cpf: true,
        remote: {
            url: "/api/findUserByCpf",
            type: "GET",
            data: {
                cpf: function() {
                    return $("#validationCpfOperador").val()
                }
            },
            dataType: 'json',
            success: function(data) {
                if (data.existe == true) {
                    console.log("Já existe o CPF cadastrado")
                } else {
                    console.log("CPF disponivel")
                }
            }
        }
    },
},
messages: {
    'cpf': {
        required: "Informe o CPF",
        remote: 'CPF já cadastrado'
    },
}
});
  • your keys are very strange ... the true return is the same way?

  • @Virgilionovic was right, I just edited

2 answers

3


Usually this return is produced as an example?

json_encode(array('existe' => 'true'));

so that the code of jquery.validation understand in the validation configuration remote need to read this key as follows:

rules: {
    cpf: {
        required:true,
        remote: {
            url:'val.php',
            type:'post',
            dataType: 'json',
            dataFilter: function(d){
                response = JSON.parse(d);
                return !response.existe;
            } 
        }
    }
}

making this configuration, the code searches if the result was true or false which is what you need to validate or not the field.

  • Thank you very much with your answer I managed to make it work after a few tests. Using the example you posted, it always stayed either valid Cpf or invalid Cpf, even if you typed already registered Cpf, then noting your answer and that of Victor, I arrived at this code: dataFilter: Function (d) { Response = JSON.parse(d); Return Response.exists ? false : true; }

  • 1

    Only change the Return line Sponse.exists; to Return Sponse.exists ? false : true;

  • 1

    @Sérgiomachado just put !. I will change

  • 1

    Perfect! was already working but so got better even

  • Could you change the date? type in the application the name of the field is client[Cpf] already in endepoint is only Cpf

  • @Sérgiomachado see if that’s it: https://answall.com/a/374004/54880 anything explains

  • not that, I had to use this technique there too, but it is the following, in the name of the field this client[phone] already in the application the endpoint was configured to only phone, example /api/findClienteByTelephone? phone=83999994444

  • @Sérgiomachado I did not understand very well his doubt, he makes the following opens another inquiry explaining the new doubt, here the staff like so each doubt for each answer ... has like?

  • 1

    I will do it anyway, not to be messy, even because it will serve also for when a person goes to seek help on the internet

  • 1

    I created another question https://answall.com/questions/376121/jquery-validate-renaando-names-complexos-brackets

Show 5 more comments

1

From what I just read in the documentation, your parameter remote request need to handle only true or false to perform the validation and display the custom message you set in the Jquery Validate.

If my line of reasoning is correct, you should change your endpoint to return only boolean in sponse or change the validation message dynamically with Jquery itself.

Edit

But searching a little I think I found a solution for you; Change the parameter success for dataFilter:

dataFilter: function(data) {        
    return data.existe ? true : false;
}
  • Yeah, I’ve seen it on several websites about this as well, but I imagine you can do something, since it identifies when the client is registered or not, return true or false. I imagine that for this you need a customized method for the library

  • I updated my answer @Sérgiomachado, see if it solves your problem.

  • It didn’t work is very strange, even identifying that Cpf is valid or not, it didn’t tick the field, but after seeing Virgilio’s answer, I did some tests and it worked, it seems what was preventing it from working properly was the lack of JSON.parse

Browser other questions tagged

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