Skip to content

Commit 64d4740

Browse files
committed
fix: enhance form validation and submission handling
1 parent 7dc7f7a commit 64d4740

File tree

2 files changed

+18
-19
lines changed

2 files changed

+18
-19
lines changed

debugging/book-library/index.html

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -26,13 +26,15 @@ <h1>Library</h1>
2626
</button>
2727

2828
<div id="demo" class="collapse">
29-
<div class="form-group">
29+
<form id="book-form" class="form-group">
3030
<label for="title">Title:</label>
3131
<input
3232
type="text"
3333
class="form-control"
3434
id="title"
3535
name="title"
36+
pattern=".*\S.*"
37+
title="Please enter a valid title (not just spaces)"
3638
required
3739
/>
3840
<label for="author">Author: </label>
@@ -41,6 +43,8 @@ <h1>Library</h1>
4143
class="form-control"
4244
id="author"
4345
name="author"
46+
pattern=".*\S.*"
47+
title="Please enter a valid author (not just spaces)"
4448
required
4549
/>
4650
<label for="pages">Pages:</label>
@@ -49,6 +53,7 @@ <h1>Library</h1>
4953
class="form-control"
5054
id="pages"
5155
name="pages"
56+
min="1"
5257
required
5358
/>
5459
<label class="form-check-label">
@@ -59,13 +64,8 @@ <h1>Library</h1>
5964
value=""
6065
/>Read
6166
</label>
62-
<input
63-
type="submit"
64-
value="Submit"
65-
class="btn btn-primary"
66-
onclick="submit()"
67-
/>
68-
</div>
67+
<button type="submit" class="btn btn-primary">Submit</button>
68+
</form>
6969
</div>
7070

7171
<table class="table" id="display">

debugging/book-library/script.js

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,13 @@
11
let myLibrary = [];
22

3-
window.addEventListener("load", function (e) {
3+
document.addEventListener("DOMContentLoaded", (e) => {
44
populateStorage();
55
render();
6+
const form = document.getElementById("book-form");
7+
form.addEventListener("submit", (e) => {
8+
e.preventDefault();
9+
submit();
10+
});
611
});
712

813
function populateStorage() {
@@ -24,17 +29,11 @@ const author = document.getElementById("author");
2429
const pages = document.getElementById("pages");
2530
const check = document.getElementById("check");
2631

27-
//check the right input from forms and if its ok -> add the new book (object in array)
28-
//via Book function and start render function
2932
function submit() {
30-
if (!title.value || !author.value || pages.value <= 0) {
31-
alert("Please fill all fields!");
32-
return false;
33-
} else {
34-
let book = new Book(title.value, author.value, pages.value, check.checked);
35-
myLibrary.push(book);
36-
render();
37-
}
33+
// Validation is now handled client side in the html
34+
let book = new Book(title.value, author.value, pages.value, check.checked);
35+
myLibrary.push(book);
36+
render();
3837
}
3938

4039
function Book(title, author, pages, check) {

0 commit comments

Comments
 (0)