Check if CPF already exists with Jquery Validate

I am validating some fields of a form from an application that was made in Ruby on Rails. In this application has some query endpoints, 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 does not exist it returns

{  
   "existe":false
}

The URl to query the CPF is as follows: http://localhost:3000/api/findUserByCpf?cpf=606.304.220-28

And the JS code of Jquery Validation , it ta returning the message in the console, but does not tick the field, 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'
    },
}
});
Author: Sérgio Machado, 2019-04-15

2 answers

Is usually this return produced as an example like this?

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

So that the code of the jquery.validation understand in the validation configuration remote you 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;
            } 
        }
    }
}

Doing this setting, the code searches whether the result was true or false which is what it needs to validate the field or not.

 3
Author: novic, 2019-04-16 00:18:44

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

If my line of reasoning is correct, you should change your endpoint to return only boolean in the response 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 to dataFilter:

dataFilter: function(data) {        
    return data.existe ? true : false;
}
 1
Author: Victor Carnaval, 2019-04-15 14:41:40