|
|
@@ -1,76 +0,0 @@
|
|
|
-// composables/useVuetifyValidation.ts
|
|
|
-import { computed, ref, inject, onMounted, onUnmounted } from 'vue'
|
|
|
-
|
|
|
-export function useVuetifyValidation(
|
|
|
- value: Ref<any>,
|
|
|
- rules: Ref<Array<(value: any) => boolean | string>>
|
|
|
-) {
|
|
|
- const hasBeenTouched = ref(false)
|
|
|
- const forceValidation = ref(false)
|
|
|
- const form = inject<any>('form', null)
|
|
|
-
|
|
|
- const errorMessages = computed(() => {
|
|
|
- if (!rules.value.length) return []
|
|
|
-
|
|
|
- const errors: string[] = []
|
|
|
- for (const rule of rules.value) {
|
|
|
- const result = rule(value.value)
|
|
|
- if (result !== true) {
|
|
|
- errors.push(typeof result === 'string' ? result : 'Erreur de validation')
|
|
|
- }
|
|
|
- }
|
|
|
- return errors
|
|
|
- })
|
|
|
-
|
|
|
- const hasError = computed(() => {
|
|
|
- if (!hasBeenTouched.value && !forceValidation.value) return false
|
|
|
- return errorMessages.value.length > 0
|
|
|
- })
|
|
|
-
|
|
|
- const isValid = computed(() => errorMessages.value.length === 0)
|
|
|
-
|
|
|
- const validationState = {
|
|
|
- id: Math.random().toString(36).substr(2, 9),
|
|
|
- isValid,
|
|
|
- errorMessages,
|
|
|
- validate: () => {
|
|
|
- forceValidation.value = true
|
|
|
- return isValid.value
|
|
|
- },
|
|
|
- reset: () => {
|
|
|
- hasBeenTouched.value = false
|
|
|
- forceValidation.value = false
|
|
|
- },
|
|
|
- resetValidation: () => {
|
|
|
- forceValidation.value = false
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- const touch = () => {
|
|
|
- hasBeenTouched.value = true
|
|
|
- }
|
|
|
-
|
|
|
- const validate = () => {
|
|
|
- forceValidation.value = true
|
|
|
- }
|
|
|
-
|
|
|
- onMounted(() => {
|
|
|
- if (form?.register) {
|
|
|
- form.register(validationState)
|
|
|
- }
|
|
|
- })
|
|
|
-
|
|
|
- onUnmounted(() => {
|
|
|
- if (form?.unregister) {
|
|
|
- form.unregister(validationState.id)
|
|
|
- }
|
|
|
- })
|
|
|
-
|
|
|
- return {
|
|
|
- hasError,
|
|
|
- errorMessages,
|
|
|
- isValid,
|
|
|
- touch,
|
|
|
- validate
|
|
|
- }
|
|
|
-}
|