feat (material): update logic validate

This commit is contained in:
riefive
2025-09-03 12:50:41 +07:00
parent e5d995b9ee
commit 6afa968b7b
2 changed files with 47 additions and 21 deletions
+36 -3
View File
@@ -1,11 +1,20 @@
<script setup lang="ts">
import Action from '~/components/pub/custom-ui/nav-footer/ba-dr-su.vue'
import { z, ZodError } from 'zod'
const errors = ref({})
const data = ref({
code: '',
name: '',
password: '',
status: '',
type: '',
stock: 0,
})
const schema = z.object({
code: z.string().min(1, 'Code must be at least 1 characters long'),
name: z.string().min(1, 'Name must be at least 1 characters long'),
type: z.string(),
stock: z.preprocess((val) => Number(val), z.number({ invalid_type_error: 'Stok harus berupa angka' })),
})
function onClick(type: string) {
@@ -15,6 +24,30 @@ function onClick(type: string) {
// do something
} else if (type === 'submit') {
// do something
const input = data.value
console.log(input)
const errorsParsed: any = {}
try {
const result = schema.safeParse(input)
if (!result.success) {
// You can handle the error here, e.g. show a message
const errorsCaptures = result?.error?.errors || []
const errorMessage = result.error.errors[0]?.message ?? 'Validation error occurred'
errorsCaptures.forEach((value: any) => {
const keyName = value?.path?.length > 0 ? value.path[0] : 'key'
errorsParsed[keyName as string] = value.message || ''
})
console.log(errorMessage)
}
} catch (e) {
if (e instanceof ZodError) {
const jsonError = e.flatten()
console.log(JSON.stringify(jsonError, null, 2))
}
}
setTimeout(() => {
errors.value = errorsParsed
}, 0)
}
}
</script>
@@ -24,7 +57,7 @@ function onClick(type: string) {
<Icon name="i-lucide-paint-bucket" class="me-2" />
<span class="font-semibold">Tambah</span> BMHP
</div>
<AppMaterialEntryForm v-model="data" />
<AppMaterialEntryForm v-model="data" :errors="errors" />
<div class="my-2 flex justify-end py-2">
<Action @click="onClick" />
</div>