teach-ict.com logo

THE education site for computer science and ICT

3. Range validation

Range validation is used when inputs have to fall between certain values.

If a form asks for the user's age, then it makes sense to check that they do not input a negative number, or a decimal. Defensive design, in this case, is writing the software code to check that these conditions are met.

These are typical situtations where range validation is useful

  • Someone has to declare they are over 18. A reasonable range is 18 to 99
  • Entering values for a calculation - is negative allowed? Is there a maximum and minimum?
  • Number of items being ordered in an online shop - it could be 1 to an upper limit
  • Luggage weight on a flight booking form - this could be 0 to an upper limit

The pseudocode below is using range validation

             age  0 # initialise age 
             WHILE age  < 18  
                 OUTPUT('Please enter your age in years, range 18 to 99')
                 age  USERINPUT()
                 IF age < 18 OR age > 99
                     OUTPUT('Not valid. The allowed range is 18 to 99 years)
                 ENDIF
             ENDWHILE  

Comment:

A variable called age is initialised and used to store the age.

The WHILE loop continues until a valid value is entered.

The entered value is checked by the IF statement that makes use of comparison operators and the OR logical operator. Should the entry be invalid, they are informed with a message.

Challenge see if you can find out one extra fact on this topic that we haven't already told you

Click on this link: Data validation