I am making a program which you need to put the Spanish document (NIF, NIE, CIF) and I need to check that the data entered is correct.
The user enters the value in a single input and it must match the NIF, or NIE, or CIF format.
This is the code I have so far:
if (document.formProveedor.NIF.value!="") {
var regNIF = /^([0-9]){8}([A-Z]){1}$/;
var regNIE = /^([A-Z]){1}([0-9]){7}([A-Z]){1}$/;
var regCIF = /^([A-Z]){1}([0-9]){8}}$/;
if(regNIF.test(document.formProveedor.NIF.value) == false) {
alert("El NIF introducido no es correcto.");
document.formProveedor.NIF.focus();
return false;
}else if(regNIE.test(document.formProveedor.NIF.value) == false){
alert("El NIE introducido no es correcto.");
document.formProveedor.NIF.focus();
return false;
}else if(regCIF.test(document.formProveedor.NIF.value) == false){
alert("El CIF introducido no es correcto.");
document.formProveedor.NIF.focus();
return false;
}
}
EXAMPLES:
NIF: 74063793K
NIE: Y9945517D
CIF: G82868043
When I fill the field with a NIF and the function is executed, I get the alert
"The NIE entered is not correct."
When I fill in the field with a NIE and the function is executed, I get the alert
"The NIF entered is not correct."
When I fill the field with a CIF and the function is executed, I get the alert
"The NIF entered is not correct."
Your problem is that you look one by one: if you enter a NIF, obviously it is not a CIF and it gives you the error, similarly it happens with a CIF or a NIE.
The simplest solution would be something like (in pseudo-code):
But a better solution would be to select the validator first, in a select, and apply it to the entered data, because a user could enter a valid value for a NIE by mistake when he really wants to enter a CIF.
I have reformulated the way you do it, and in my opinion you should use some kind of dropdown to choose what kind of validation you want, so you don't have to write many lines comparing that it is only NIF, CIF, NIE, etc.
First of all I have made an array of objects with their type and validation.
With that I have made a function
validar
that takes two parameters:tipo
andnumero
, where the type is NIE, NIF, DNI, CIF... and the number is the value you want to check.To call it would be like this:
Remember that to fill in the parameter
tipo
, it would be nice to use a dropdown .