Reusable Validation
Validates the email and age on a sign-up form.
- Level
- Intermediate
- Topic:
- Subprocesses & functions
- Concepts:
- Input & output
- Functions
- Logic
- Repetir
- Text
Run, change and debug this example in your browser.
What you'll learn
Each Funcion returns a Logico value, so you can use it directly in a Si or a Hasta Que. Conditions are combined with Y and negated with NO.
Code
Funcion valido <- EsCorreoValido(correo) Definir valido Como Logico Definir i, arrobas, posicionArroba Como Entero arrobas <- 0 posicionArroba <- 0 Para i <- 1 Hasta Longitud(correo) Hacer Si Subcadena(correo, i, i) = "@" Entonces arrobas <- arrobas + 1 posicionArroba <- i FinSi FinPara valido <- arrobas = 1 Y posicionArroba > 1 Y posicionArroba < Longitud(correo)FinFuncionFuncion valido <- EsEdadValida(edad) Definir valido Como Logico valido <- edad >= 0 Y edad <= 120FinFuncionAlgoritmo Registro Definir correo Como Caracter Definir edad Como Entero Repetir Escribir "Correo electrónico:" Leer correo Si NO EsCorreoValido(correo) Entonces Escribir "Ese correo no parece válido." FinSi Hasta Que EsCorreoValido(correo) Repetir Escribir "Edad:" Leer edad Si NO EsEdadValida(edad) Entonces Escribir "Escribe una edad entre 0 y 120." FinSi Hasta Que EsEdadValida(edad) Escribir "Registro completo: ", correo, ", ", edad, " años."FinAlgoritmoFlowchart
Each block in the flowchart matches one instruction in the code.
Sample run
This is what the program shows when it runs. The answers typed by the user are highlighted.
Correo electrónico:User answer: ana.gmail.comEse correo no parece válido.Correo electrónico:User answer: ana@gmail.comEdad:User answer: 150Escribe una edad entre 0 y 120.Edad:User answer: 17Registro completo: ana@gmail.com, 17 años.
Challenge
Add an EsNombreValido function that requires at least 3 letters, and ask for the name first.
Show hint
Use Longitud inside the function and repeat the same Repetir ... Hasta Que pattern.
Related examples
Tic-Tac-Toe
The classic three-in-a-row game for two players.
AdvancedPassword Check
Keeps asking for a password until it has at least 8 characters.
BeginnerQuicksort
Picks a pivot, splits smaller from larger values and sorts each side recursively.
Advanced