I have a form where I try to validate the RFC of a provider. If the supplier 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 aonblur = "ValidaRFC(this.value)"
The problem is not in the RegExp, but in
$(function(){ ... })
: according to the jQuery documentation the expression$(function(){ ... })
is equivalent:Which means that you are not defining the function
ValidaRFC
, but executing it when the document loads. So, whenblur
the textbox event is fired, your function is not executed (because it is undefined).Solution: (Edited)
Thus, in the event
blur
of the text box the function will be fired as expected.$(document).ready(function(){ tu codigo })
must be replaced by$(function() { tu codigo })
, so jquery will take the declared functions, because if not, it will show you that the function has not been declared