Practical software engineering foundations · Lesson 54 of 60 · Code lesson, JavaScript or Python · Optional
Data validation
Data validation checks that input is acceptable before the program uses it.
Check the type, the range, the length and the format, and reject anything that does not fit.
Validate on the server even when the page already checked, because users can bypass the page.
Worked example
In JavaScript, Number.isInteger(age) is false for NaN, so it catches text that is not a number.
const age = Number("25");
console.log(Number.isInteger(age) && age >= 0 && age <= 120 ? "valid" : "invalid");Output: valid
In Python, int(text) raises a ValueError when the text is not a whole number, which try and except can catch.
age = int("25")
print("valid" if 0 <= age <= 120 else "invalid")Output: valid
Your turn
The program reads an age and always prints valid. Make it print valid only for whole numbers from 0 to 120, and invalid for anything else, such as -5, 150 or abc.
Your program is checked with these 4 inputs:
Input:
25
Expected output:
valid
Input:
-5
Expected output:
invalid
Input:
abc
Expected output:
invalid
Input:
150
Expected output:
invalid
Loading your practice…
Preparing your workspace…