Input validation is a loop that keeps asking until the value meets a rule. The rule might be a range, a length or a presence check, and the loop condition describes the invalid case.
This lesson belongs to pseudocode for the applicable syllabus. It builds on tracing assignment and comparison, and connects to the wider ideas in validation, verification and testing.
How do I turn a rule into a loop?
State the rule in words, then write the invalid condition, because the loop repeats while the data is wrong.
| Check | Rule | Invalid condition |
|---|---|---|
| Range | Age from 12 to 18 | Age < 12 OR Age > 18 |
| Length | Code has exactly 6 characters | LENGTH(Code) <> 6 |
| Presence | Name is not empty | Name = "" |
The pattern is: read once, then repeat while invalid, asking again inside the loop.
INPUT Age
WHILE Age < 12 OR Age > 18 DO
OUTPUT "Enter an age from 12 to 18"
INPUT Age
ENDWHILE
Worked example
Trace the loop above when the user types 25, then 9, then 14.
| Step | Age | Condition (Age < 12 OR Age > 18) | Action |
|---|---|---|---|
| first INPUT | 25 | 25 > 18, so TRUE | prompt, INPUT again |
| second INPUT | 9 | 9 < 12, so TRUE | prompt, INPUT again |
| third INPUT | 14 | FALSE, FALSE, so FALSE | loop ends |
The prompt is output twice and Age finishes as 14. Check: 14 is not below 12 and not above 18, so it is allowed.
Some questions also accept the check in words: “Repeat the input while the age is less than 12 or more than 18.” Name the rule precisely and avoid pointing to a built-in method.
The mistake to watch for
A common slip is using AND where OR is needed.
Mistaken condition:
WHILE Age < 12 AND Age > 18 DONo number is both below 12 and above 18, so the condition is always FALSE. The loop never runs, and 25 is accepted.
The correction is OR for the invalid case. A second slip is using the valid condition in a WHILE: WHILE Age >= 12 AND Age <= 18 repeats the prompt for good values and stops for bad ones.
If you prefer to write the valid rule, use REPEAT ... UNTIL Age >= 12 AND Age <= 18.
Check yourself
1. Write the invalid condition for a mark that must be from 0 to 100.
Show answer
Mark < 0 OR Mark > 100
2. A code must have exactly 5 characters. The user types “AB12”. Does the loop repeat?
Show answer
LENGTH(“AB12”) is 4, and 4 <> 5 is TRUE. Yes, the loop repeats and asks again.
3. Does a range check on age stop the user typing 15 when they are really 17?
Show answer
No. 15 is inside the range, so it passes. Validation checks that the value is reasonable, not that it is true.
Where this leads next
Validation loops are one of the most common places for termination mistakes, so continue to repairing a loop termination condition. Practise stepping the code in the restricted pseudocode trace trainer.
A teacher on our online one-to-one Computer Science tuition can give you fresh validation scenarios and check each condition you write.