Lucas Bueno Lucas Bueno - 7 months ago 11
Javascript Question

.validate rule: check jquery var

So, i'm trying to take a jQuery var and use it as a rule for the .validate plugin.
The var comes from a function that runs a function and give 1 for true and 0 for false, the problem is that i can't make the rule return true or false for the validate function. The code reads:

$.validator.addMethod("cpfc", function(){
if (($(CPF.valida($(cpf).val())).size()) === '1' )
return true;
return false;

, depends on the function check, I ran this function on the console and it's returning the correct values.

Any help will be appreciated


You have a semi-colon between the if and else statement which will be causing a syntax error. Also note that size() (aside from being deprecated) returns an integer, so your current code will always return false as you compare it to a string. It's now recommended to use the length property instead:

$.validator.addMethod("cpfc", function(){
    if ($(CPF.valida($(cpf).val())).length === 1) {
        return true
    } else {
        return false

This can be further reduced to just

$.validator.addMethod("cpfc", function(){
    return $(CPF.valida($(cpf).val())).length === 1;

You should also ensure that the CPF object and cpf variable are in scope and hold the values you expect when called from within the validator method.