added validation when adding a book

This commit is contained in:
2025-09-24 17:06:39 +02:00
parent 8432902df1
commit 2f0a9b5127
7 changed files with 105 additions and 13 deletions

View File

@@ -1,5 +1,5 @@
<script setup>
import { ref } from 'vue'
import { ref, reactive, computed } from 'vue'
import { postBook } from './api.js'
import { useRouter, useRoute } from 'vue-router'
@@ -9,10 +9,36 @@
title: "",
author: ""
});
const errors = ref(null)
const titleError = computed(() => {
return extractErrorFromField("Title");
})
const authorError = computed(() => {
return extractErrorFromField("Author");
})
function extractErrorFromField(fieldName) {
if (errors.value === null) {
return "";
}
const titleErr = errors.value.find((e) => e["field"] === fieldName);
if (typeof titleErr !== 'undefined') {
return titleErr.error
} else {
return "";
}
}
function onSubmit(e) {
postBook(book);
router.push('/');
postBook(book)
.then((res) => {
if (res.ok) {
router.push('/');
return;
} else {
res.json().then((json) => (errors.value = json));
}
})
}
</script>
@@ -21,14 +47,17 @@
<div class="field">
<label class="label">Title</label>
<div class="control">
<input class="input" type="text" v-model="book.title" placeholder="Title">
<input :class="'input ' + (titleError ? 'is-danger' : '')" type="text" maxlength="300"
required v-model="book.title" placeholder="Title">
</div>
<p v-if="titleError" class="help is-danger">{{titleError}}</p>
</div>
<div class="field">
<label class="label">Author</label>
<div class="control">
<input class="input" type="text" v-model="book.author" placeholder="Author">
<input :class="'input ' + (authorError ? 'is-danger' : '')" type="text" maxlength="100" v-model="book.author" placeholder="Author">
</div>
<p v-if="authorError" class="help is-danger">{{authorError}}</p>
</div>
<div class="field">
<div class="control">

View File

@@ -3,13 +3,13 @@ import { ref } from 'vue'
const baseUrl = "http://localhost:8080"
function useFetch(url) {
const data = ref(null)
const error = ref(null)
const data = ref(null);
const error = ref(null);
fetch(url)
.then((res) => res.json())
.then((json) => (data.value = json))
.catch((err) => (error.value = err))
.catch((err) => (error.value = err));
return { data, error }
}
@@ -19,11 +19,11 @@ export function getBooks() {
}
export function postBook(book) {
fetch(baseUrl + '/book', {
return fetch(baseUrl + '/book', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(book.value)
});
})
}