Skip to content

Commit fbccd0a

Browse files
Improve form validation and submission logic; ensure fields are trimmed and reset correctly
1 parent b2e66c1 commit fbccd0a

1 file changed

Lines changed: 32 additions & 14 deletions

File tree

debugging/book-library/script.js

Lines changed: 32 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -28,20 +28,38 @@ const check = document.getElementById("check");
2828
//check the right input from forms and if its ok -> add the new book (object in array)
2929
//via Book function and start render function
3030
function submit() {
31-
if (
32-
title.value === "" ||
33-
author.value === "" ||
34-
pages.value === "" ||
35-
!check.checked //if the checkbox is not checked, it will be false, so we need to check if its not checked
36-
) {
37-
alert("Please fill all fields!");
31+
32+
// 1. Preprocess and store cleaned values in variables / removes spaces from the beginning and end
33+
const cleanTitle = title.value.trim();
34+
const cleanAuthor = author.value.trim();
35+
36+
// Convert string input to a Number for calculation/validation
37+
const pageCount = Number(pages.value);
38+
const isRead = check.checked;
39+
40+
// 2. VALIDATION: // Check if strings are empty after trimming spaces
41+
if (cleanTitle === "" || cleanAuthor === "") {
42+
alert("Title and Author cannot be empty!");
43+
return false;
44+
}
45+
// Check if page count is a valid number and greater than 0
46+
if (isNaN(pageCount) || pageCount <= 0) {
47+
alert("Please enter a valid number of pages!");
3848
return false;
39-
} else {
40-
let book = new Book(title.value, author.value, pages.value, check.checked);
41-
myLibrary.push(book);
49+
}
50+
51+
// 3. If all validations pass, create a new Book object and add it to the library
52+
let book = new Book(cleanTitle, cleanAuthor, pageCount, isRead);
53+
myLibrary.push(book);
54+
55+
// 4. Clear the form fields after submission
56+
title.value = "";
57+
author.value = "";
58+
pages.value = "";
59+
check.checked = false;
60+
4261
render();
4362
}
44-
}
4563

4664
class Book {
4765
constructor(title, author, pages, check) {
@@ -68,9 +86,9 @@ function render() {
6886
let pagesCell = row.insertCell(2);
6987
let wasReadCell = row.insertCell(3);
7088
let deleteCell = row.insertCell(4);
71-
titleCell.innerHTML = myLibrary[i].title;
72-
authorCell.innerHTML = myLibrary[i].author;
73-
pagesCell.innerHTML = myLibrary[i].pages;
89+
titleCell.textContent = myLibrary[i].title;
90+
authorCell.textContent = myLibrary[i].author;
91+
pagesCell.textContent = myLibrary[i].pages;
7492

7593
//add and wait for action for read/unread button
7694
let changeBut = document.createElement("button");

0 commit comments

Comments
 (0)