108 lines
2.2 KiB
TypeScript
108 lines
2.2 KiB
TypeScript
import type { ZodError } from 'zod'
|
|
import type { FormErrors } from '~/types/error'
|
|
|
|
/**
|
|
* Composable untuk menangani form validation errors seperti Laravel
|
|
* Mengkonversi ZodError menjadi format yang mudah digunakan di template
|
|
*/
|
|
export function useFormErrors() {
|
|
const errors = ref<FormErrors>({})
|
|
|
|
/**
|
|
* Set errors dari ZodError
|
|
*/
|
|
function setFromZodError(zodError: ZodError) {
|
|
const newErrors: FormErrors = {}
|
|
|
|
zodError.errors.forEach((error) => {
|
|
const field = error.path.join('.')
|
|
newErrors[field] = {
|
|
message: error.message,
|
|
code: error.code,
|
|
path: error.path,
|
|
}
|
|
})
|
|
|
|
errors.value = newErrors
|
|
}
|
|
|
|
/**
|
|
* Set errors manual (untuk error dari API response)
|
|
*/
|
|
function setErrors(newErrors: FormErrors) {
|
|
errors.value = newErrors
|
|
}
|
|
|
|
/**
|
|
* Set error untuk field tertentu
|
|
*/
|
|
function setError(field: string, message: string, extra: Record<string, any> = {}) {
|
|
errors.value[field] = {
|
|
message,
|
|
...extra,
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Hapus error untuk field tertentu
|
|
*/
|
|
function clearError(field: string) {
|
|
delete errors.value[field]
|
|
}
|
|
|
|
/**
|
|
* Hapus semua errors
|
|
*/
|
|
function clearErrors() {
|
|
errors.value = {}
|
|
}
|
|
|
|
/**
|
|
* Cek apakah ada error untuk field tertentu
|
|
*/
|
|
function hasError(field: string): boolean {
|
|
return !!errors.value[field]
|
|
}
|
|
|
|
/**
|
|
* Ambil error message untuk field tertentu
|
|
*/
|
|
function getError(field: string): string | null {
|
|
return errors.value[field]?.message || null
|
|
}
|
|
|
|
/**
|
|
* Cek apakah ada error apapun
|
|
*/
|
|
const hasErrors = computed(() => Object.keys(errors.value).length > 0)
|
|
|
|
/**
|
|
* Ambil semua error messages sebagai array
|
|
*/
|
|
const errorMessages = computed(() =>
|
|
Object.values(errors.value).map(error => error.message),
|
|
)
|
|
|
|
/**
|
|
* Ambil error pertama (untuk menampilkan alert general)
|
|
*/
|
|
const firstError = computed(() => {
|
|
const firstKey = Object.keys(errors.value)[0]
|
|
return firstKey ? errors.value[firstKey] : null
|
|
})
|
|
|
|
return {
|
|
errors: readonly(errors),
|
|
setFromZodError,
|
|
setErrors,
|
|
setError,
|
|
clearError,
|
|
clearErrors,
|
|
hasError,
|
|
getError,
|
|
hasErrors,
|
|
errorMessages,
|
|
firstError,
|
|
}
|
|
}
|