Skip to content

Commit eea5314

Browse files
committed
Refactor addBook function for improved validation and sanitization
1 parent ea76889 commit eea5314

File tree

1 file changed

+25
-16
lines changed

1 file changed

+25
-16
lines changed

debugging/book-library/script.js

Lines changed: 25 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -22,31 +22,40 @@ const check = document.getElementById("check");
2222

2323
// renamed so we don’t conflict with form.submit()
2424
function addBook() {
25-
if (
26-
!bookTitle.value.trim() ||
27-
!author.value.trim() ||
28-
!pages.value.trim()
29-
) {
25+
// Get and sanitize values once
26+
const titleValue = bookTitle.value.trim();
27+
const authorValue = author.value.trim();
28+
const pagesValue = pages.value.trim();
29+
const isRead = check.checked;
30+
31+
// Basic empty validation
32+
if (!titleValue || !authorValue || !pagesValue) {
3033
alert("Please fill all fields!");
3134
return;
3235
}
3336

34-
const book = new Book(
35-
bookTitle.value.trim(),
36-
author.value.trim(),
37-
pages.value.trim(),
38-
check.checked
39-
);
37+
// Validate page number properly
38+
const pagesNumber = Number(pagesValue);
39+
if (!Number.isInteger(pagesNumber) || pagesNumber <= 0) {
40+
alert("Please enter a valid positive page count!");
41+
return;
42+
}
4043

44+
// Create the book with sanitized values
45+
const book = new Book(titleValue, authorValue, pagesNumber, isRead);
46+
47+
// Save to library
4148
myLibrary.push(book);
49+
50+
// Re-render UI
4251
render();
4352
}
4453

45-
function Book(bookTitle, author, pages, check) {
46-
this.bookTitle = bookTitle;
47-
this.author = author;
48-
this.pages = pages;
49-
this.check = check;
54+
function Book(titleValue, authorValue, pagesNumber, isRead) {
55+
this.bookTitle = titleValue;
56+
this.author = authorValue;
57+
this.pages = pagesNumber;
58+
this.check = isRead;
5059
}
5160

5261

0 commit comments

Comments
 (0)