How to declare a function with jQuery?

I have a form where I try to validate a provider'S RFC. If the provider is a legal person it must have 12 characters, and if it is a natural person it must have 13.

I use the following function to validate:

$(function ValidaRFC($rfc) {
        var strCorrecta;
        strCorrecta = $rfc;
        if ($("#TipoPersona :selected").text() == "Moral") {
            if ($($rfc).length == 12) {
                var valid = '^(([A-Z]|[a-z]){3})([0-9]{6})((([A-Z]|[a-z]|[0-9]){3}))';
            }
        }
        if ($("#TipoPersona :selected").text() == "Fisica") {
            if ($($rfc).length == 12) {
                var valid = '^(([A-Z]|[a-z]|\s){1})(([A-Z]|[a-z]){3})([0-9]{6})((([A-Z]|[a-z]|[0-9]){3}))';
            }

        }
        var validRfc = new RegExp(valid);
        var matchArray = strCorrecta.match(validRfc);
        if (matchArray == null) {
            alert('el rfc es incorrecto');

            return false;
        }
    });

But nothing happens, even if I put more than 12 or 13 characters, it lets me save the provider.

In the rfc input I use a onblur = "ValidaRFC(this.value)"

 1
Author: Mariano, 2016-08-12

1 answers

The problem is not in the Regexps, but in $(function(){ ... }): according to the documentation of jQuery the expression $(function(){ ... }) is equivalent:

$(document).ready(function(){ ... })

Which means you're not defining the ValidaRFC function, but executing it when the document loads. Thus, when the blurevent is fired from the textbox, your function is not executed (because it is undefined).

Solution: (Edited)

function ValidaRFC($rfc) { //Quité el '$(' de aquí...
    var strCorrecta;
    strCorrecta = $rfc;
    var longitudCorrecta = false;
    var valid;

    if ($("#TipoPersona :selected").text() == "Moral") {
        longitudCorrecta = (strCorrecta.length === 12);
        valid = '^(([A-Z]|[a-z]){3})([0-9]{6})((([A-Z]|[a-z]|[0-9]){3}))';          
    }
    if ($("#TipoPersona :selected").text() == "Fisica") {
        longitudCorrecta = (strCorrecta.length === 13);
        valid = '^(([A-Z]|[a-z]|\s){1})(([A-Z]|[a-z]){3})([0-9]{6})((([A-Z]|[a-z]|[0-9]){3}))';            
    }
    if(!longitudCorrecta){
        alert('el rfc es incorrecto');
        return false;
    }
    var validRfc = new RegExp(valid);
    var matchArray = strCorrecta.match(validRfc);
    if (matchArray == null) {
        alert('el rfc es incorrecto');

        return false;
    }
}; //...y el paréntesis de cierre aquí

Thus, the blur event in the text box will trigger the function as you expected.

 2
Author: Roimer, 2016-08-13 00:38:05