Skip to content

Commit 6e184cf

Browse files
committed
Update addBook function with improved validation and optimized input handling.
1 parent 7e65169 commit 6e184cf

File tree

1 file changed

+18
-4
lines changed

1 file changed

+18
-4
lines changed

debugging/book-library/script.js

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,29 @@ const check = document.getElementById("check");
2020

2121
// Add a new book to the library
2222
function addBook() {
23-
if (!title.value.trim() || !author.value.trim() || !pages.value.trim()) {
23+
const titleValue = title.value.trim();
24+
const authorValue = author.value.trim();
25+
const pagesValue = pages.value.trim();
26+
const isRead = check.checked;
27+
28+
// Validate input fields
29+
if (!titleValue || !authorValue || !pagesValue) {
2430
alert("Please fill all fields!");
25-
return;
31+
return false;
32+
}
33+
34+
// Validate "number of pages" field
35+
const pagesNumber = parseInt(pagesValue, 10);
36+
if (isNaN(pagesNumber) || pagesNumber <= 0) {
37+
alert("Please enter a valid number of pages!");
38+
return false;
2639
}
27-
let book = new Book(title.value.trim(), author.value.trim(), pages.value, check.checked);
40+
41+
// Create a new book and add it to the library
42+
const book = new Book(titleValue, authorValue, pagesNumber, isRead);
2843
myLibrary.push(book);
2944
render();
3045
}
31-
3246
// Book constructor
3347
function Book(title, author, pages, read) {
3448
this.title = title;

0 commit comments

Comments
 (0)