I am using the vee-validate Field in my Nuxt 3 application to create a generic component which I am reusing in multiple places by passing different types and other associated information.
I came across an issue where if I use the type as number then I am unable to pass the 0 as a leading entry if I pass it is automatically deleted for some reason. I found out that it is due to HTML 5 restriction. If I change to type as text then it works fine but the problem is that it accepts the alphabets as well which I want to avoid.
I have additional yup based validation on my Field but the validation kicks in only during the submit button click. Hence I want to prevent the user from entering the alphabet at all. By using numbers I can make sure that the user cannot enter the alphabets at all but the problem is leading 0s issue.
Is there a way I can use the type as text and then add an additional patter to my Field component so that it does not accept the alphabets at all? With this, I can fix both the issues. or How to make sure to keep the type as number only during the usage and pass the leading 0s to the ValueField? Currently leading 0s or omitted
Following is my code:
ValueField.vue:
<template>
<Field
v-model="inputFieldValue"
:value="modelValue"
@input="updateValue"
:name="name"
:type="type"
/>
</div>
<ErrorMessage :name="name" class="text-red-500 mt-2 italic" />
</template>
<script setup>
import { Field, ErrorMessage } from "vee-validate";
const props = defineProps({
type: {
type: String, // type of input field ex: text, number
required: false,
},
name: {
type: String, // placeholder for the Input field
required: false,
},
model: {
type: String, // name of the corresponding model for input field
required: false,
},
modelValue: {
type: [String, Number, Boolean, null], // name of the corresponding model for input field
required: false,
},
});
const defaultFieldValue = toRef(props, "modelValue");
const inputFieldValue = ref(defaultFieldValue.value);
const emits = defineEmits(["inputChange", "update:modelValue"]);
// Emit the updated modelValue when the inputField value changes
watchEffect(() => {
emits("update:modelValue", inputFieldValue.value);
});
// Watch the modelValue prop and update field when it changes
watch(
() => props.modelValue,
(newVal) => {
inputFieldValue.value = newVal;
}
);
const updateValue = (event) => {
emits("update:modelValue", event.target.value);
};
const inputChange = () => {
emits("inputChange", props.model, inputFieldValue.value);
};
</script>
Its usage:
<ValueField
v-model="myNumber"
:name="'myNumber'"
:type="'number'"
/>
Since its generic component I do not wish to create additional method in ValueField.vue as its in different places differnet way using the meth