By the end of this lesson, you will know how to build a validated expense form using JavaScript.
When you track your spending, filling out forms is part of the process. For instance, when you buy groceries, you might want to record the amount spent and the date. A validated expense form ensures that the information entered is correct before submission, helping you keep accurate records.
File: expense_form.html
<!DOCTYPE html>
<html>
<head>
<title>Expense Tracker</title>
<script>
function validateForm() {
var description = document.getElementById("description").value;
var amount = document.getElementById("amount").value;
var date = document.getElementById("date").value;
if (description === "" || amount === "" || date === "") {
alert("Please fill in all fields.");
return false;
}
if (isNaN(amount) || amount <= 0) {
alert("Please enter a valid positive number for amount.");
return false;
}
return true;
}
</script>
</head>
<body>
<h1>Expense Form</h1>
<form onsubmit="return validateForm()">
<label for="description">Description:</label> <input type="text" id="description"><br>
<label for="amount">Amount:</label> <input type="text" id="amount"><br>
<label for="date">Date:</label> <input type="date" id="date"><br>
<input type="submit" value="Add Expense">
</form>
</body>
</html>
Expected Output:
A form asking for a description, amount, and date, along with validation messages if any field is left empty or incorrect.
The validateForm function checks if the fields are filled. If not, it alerts the user. The check for a valid amount prevents negative numbers and non-numeric inputs. This is crucial for accurate expense tracking.
Now it’s your turn! Create a form with at least three fields: description, amount, and date. Add validation to ensure no fields are empty and that the amount is a positive number. Use the code example above as a guide.
<!DOCTYPE html>
<html>
<head>
<title>Expense Tracker</title>
<script>
function validateForm() {
var description = document.getElementById("description").value;
var amount = document.getElementById("amount").value;
var date = document.getElementById("date").value;
if (description === "" || amount === "" || date === "") {
alert("Please fill in all fields.");
return false;
}
if (isNaN(amount) || amount <= 0) {
alert("Please enter a valid positive number for amount.");
return false;
}
return true;
}
</script>
</head>
<body>
<h1>Expense Form</h1>
<form onsubmit="return validateForm()">
<label for="description">Description:</label> <input type="text" id="description"><br>
<label for="amount">Amount:</label> <input type="text" id="amount"><br>
<label for="date">Date:</label> <input type="date" id="date"><br>
<input type="submit" value="Add Expense">
</form>
</body>
</html>