Skip to content

Commit 2417ca4

Browse files
committed
fix(validation): require pages to be a positive integer
- Use valueAsNumber and input validity (valueMissing, rangeUnderflow, stepMismatch) - Reject non-numeric and decimal values; enforce min=1 and step=1 - Preserve existing submit handling and notice behavior
1 parent 9c3c39f commit 2417ca4

1 file changed

Lines changed: 19 additions & 8 deletions

File tree

debugging/book-library/script.js

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ const authorInput = document.getElementById("author");
3333
const pagesInput = document.getElementById("pages");
3434
const readCheckbox = document.getElementById("check");
3535

36-
// Non-blocking success message using CSS animation; no inline styles, no setTimeout
36+
// Non-blocking success message using CSS animation; JS only toggles classes
3737
function showSuccess(message) {
3838
const root = document.getElementById("alerts");
3939
if (!root) return;
@@ -56,22 +56,33 @@ function showSuccess(message) {
5656
root.appendChild(alertEl);
5757
}
5858

59-
//check the right input from forms and if its ok -> add the new book (object in array)
60-
//via Book function and start render function
59+
// Check the right input from forms and if it's ok -> add the new book (object in array)
60+
// via Book function and start render function
6161
function submit() {
6262
const title = titleInput.value.trim();
6363
const author = authorInput.value.trim();
64-
const pages = Number(pagesInput.value);
6564

6665
// Validate title and author
6766
if (title === "" || author === "") {
6867
alert("Title and author cannot be empty.");
6968
return;
7069
}
7170

72-
// Validate pages
73-
if (Number.isNaN(pages) || pages <= 0) {
74-
alert("Pages must be a positive number.");
71+
// Read and validate pages as a positive integer
72+
const pages = pagesInput.valueAsNumber;
73+
const v = pagesInput.validity;
74+
75+
if (v.valueMissing || !Number.isFinite(pages)) {
76+
alert("Pages is required and must be a number.");
77+
return;
78+
}
79+
if (v.rangeUnderflow || pages < 1) {
80+
alert("Pages must be at least 1.");
81+
return;
82+
}
83+
// Enforce whole numbers only (reject decimals like 3.5)
84+
if (v.stepMismatch || !Number.isInteger(pages)) {
85+
alert("Pages must be a whole number.");
7586
return;
7687
}
7788

@@ -108,7 +119,7 @@ function render() {
108119

109120
titleCell.textContent = book.title;
110121
authorCell.textContent = book.author;
111-
pagesCell.textContent = book.pages;
122+
pagesCell.textContent = String(book.pages);
112123

113124
// Read/unread toggle button
114125
const changeBut = document.createElement("button");

0 commit comments

Comments
 (0)