I’m trying to validate an ID.
I have this class called ManejadorTickets in which -among others things- I call the method to validate an ID (the ID is the Cedula is something like SSN in USA).
public void venderTicket ()
{
// more code...
Console.Write("\nCedula: ");
string cedula = Validador.validarCedula(Console.ReadLine().Trim());
// more code...
}
This is my validarCedula method in Validador class.
public static String validarCedula (string cedula)
{
// Limpiar la entrada de caracteres extraños
cedula = cedula.Replace("-", "");
cedula = cedula.Replace(" ", "");
// Debe tener 11 caracteres
if (cedula.Length != 11)
{
Impresor.imprimirOpExitosa(cedula.Length.ToString());
Impresor.imprimirError("La cedula debe tener 11 digitos", "Cedula: ");
validarCedula(Console.ReadLine().Trim());
}
// Todos los caracteres deben ser numeros
char[] arrayLetras = cedula.ToCharArray();
foreach (char c in arrayLetras)
{
if (NUMEROS.IndexOf(c) == -1)
{
Impresor.imprimirError("Todos los caracteres deben ser numericos." +
" Los guiones o espacios no se toman en cuenta.", "Cedula: ");
validarCedula(Console.ReadLine().Trim());
}
}
return cedula;
}
The method above eliminate hyphens and space from the input. Is also check if the input has exactly 11 characters and if all characters are numbers.
Note: NUMBERS is a constant I declared at the beginning of the class
private const string NUMEROS = "0123456789";
But when I running the program, enter a wrong value as a Cedula (to test my validation method) such as “foo”, it happens what should happens (ask for the value again). So far so good, now when I type a correct value such as 00114905656 (all numbers and 11 digits) it ask again for a value and that should not happen because the last entered value was correct.
I tried debugging my applications and I see that the method execute as it should, but when the compiler execute the statement return cedula; (last sentence in the method) it jumps to the first validarCedula(Console.ReadLine().Trim()); statement that’s the one inside the if (cedula.Length != 11) statement. And I don’t understand WHY that happens. When the return is executed the method is supposed to finish.
You are calling
validarCedulafrom within itself. This is called recursion.Try stepping through from the beginning. Look at the call-stack window.
I think you need to restructure your program a bit.
Try implementing
validarCedulamore like this:And then do this in your
vendorTicketfunction, so you still get it to re-prompt until it passes: