Input validation
An input validation algorithm is used to ensure that the data entered by a user is acceptable. For example, if a program were to ask for a score between 0 and 50, an input validation algorithm would be used to ensure that values below 0 and above 50 were rejected.
There are a range of contexts for input validation over and above ensuring that a number entered is within a range. Input validation algorithms can be created to ensure that a string entry is a certain length or to make sure that a required combination of characters is used.
At Higher Computing Science level, it is common to have to validate the input of items that are to be stored in an array.
Example
A panel of judges at a dance competition are asked to enter the scores for five dancers. The scores should be between 0 and 50.
In this example a fixed loop is used to ensure that the marks for all five dancers can be entered. Within the fixed loop there is a conditional loop which is used to validate the users input.
Reference language
Line 1 FOR counter FROM 0 TO 4 DoLine 2 RECEIVE score [counter] FROM (INTEGER) KEYBOARDLine 3 WHILE score [counter] ˂0 OR score [counter] ˃ 50 DOLine 4 SEND (“The score you entered was not valid; please enter a score between 0 and 50”) TO DISPLAYLine 5 RECEIVE score [counter] FROM (INTEGER) KEYBOARDLine 6 END WHILELine 7 END FORImportant points
- The counter/index value starts at 0 , as in all reference language examples indexing begins at 0.
- Some of the high level languages used in schools will not index from 0 but will index from 1.
- The score array would use locations 0, 1, 2, 3 and 4 to store five values, hence the need to make sure that the counter begins at 0 rather than 1.
- If the user enters a valid number on line two then line three will not force the program to execute lines four to six.
- Line three only initiates a conditional loop if the value entered in line two is less than zero or greater than fifty.
- If a number outside of the range is entered in line five, the program will continue to execute the conditional loop until a valid number is entered.