| Level Navigation: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | Current Level: 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 |
Add input validation to handle empty user input gracefully.
Why validation matters: Professional applications always check user input before processing it. This prevents errors and provides helpful feedback to users.
Add a condition for when the input is empty:
Before we start, let’s review how if statements work! You used these in Week 3 for game controls and sprite interactions.
if (condition) {
// code to run if condition is true
}
Checking if a key is pressed:
if (keyDown("LEFT_ARROW")) {
player.x = player.x - 5;
}
Checking if a sprite is off screen:
if (platform.y > 400) {
platform.y = -50; // move back to top
}
Checking if sprites are touching:
if (player.isTouching(item)) {
score = score + 1;
item.x = randomNumber(50, 350);
}
Checking if input is empty:
var userInput = "";
userInput = getValue("user-chat-input");
if (userInput === "") {
// show warning message that no input is there
} else {
// User has input a prompt. OK to proceed with query.
}
You’ll need to check if the input field is empty. An empty input field has a value of "" (empty string). You can test for this condition using === to compare the input’s value.
Checking for empty input? You’ll need to use conditional logic to check if the input is empty and show different messages. Check out the Conditional Logic section in SNIPPETS.md for examples and the Helper Functions section for styling functions.
Next: Level 26 - Valid Input Handling
| Level Navigation: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | Current Level: 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 |