3.2.11 - Data validation routines (C#)

3.2.11 - Data validation routines (C#)

Check that user input meets a problem's rules and repeat input when it is invalid. Native written answers use C#. C# execution is unavailable here; the runnable activity is an optional Python demonstration.

Checking validity

Validation checks whether entered data is acceptable under stated rules before a program uses it.

Validation

Checking whether data is feasible or acceptable, for example whether a percentage lies in a permitted range. It does not prove the data is factually correct.

A mark of 566 cannot be a percentage on a 0–100 scale, so a range check rejects it. If the real mark is 65 but the user enters 56, both values pass the range rule. Validation cannot discover that factual mistake without other evidence. Define the problem's rule first, then select a matching check.

This differs from authentication, which checks identity using credentials such as a username and its associated password. A long enough password may pass a length check while being the wrong password for an account. Both routines help robustness/security, but answer different questions.

For GCSE examination inputs, assume errors do not concern data type. You still convert numeric text for native arithmetic, but are not required to implement data-type checks, exceptions or TryParse. The required simple routines here are length, presence and range checks.

Length, presence and range checks

Choose a check that directly expresses the data rule, paying attention to whether boundary values are allowed.

C#
bool longEnough = password.Length >= 8;
bool namePresent = customerName != "";
bool scoreInRange = score >= 1 && score <= 10;

The length check accepts eight or more characters; a length of seven fails. The presence check rejects the empty string. It does not reject spaces unless the requirements also demand that rule. The range check accepts both 1 and 10. An invalid range condition is score < 1 || score > 10, using OR because either failure is enough to reject the input.

Plan representative tests before accepting the routine:

Score inputExpected resultPurpose
5AcceptNormal, typical valid value
0RejectImmediately below the lower boundary
1AcceptLowest permitted boundary value
10AcceptHighest permitted boundary value
11RejectImmediately above the upper boundary
25RejectErroneous value well outside the range

The four boundary values reveal missing equality and limits shifted by one. Erroneous means invalid for the stated rule; boundary and erroneous descriptions can overlap for immediately-outside values. Apply the same reasoning to string length and the empty string.

Continue this lesson.

You’re previewing NovaLearn without an account. Create a free account to read the rest.

Create free account