I am working on a form that includes a phone number input field, and I want the formatting of the number to change to a standard telephone number format as the user types. Can someone provide guidance on how this can be achieved using JavaScript and Vue 3?
My main component is AppointmentForm.vue
<div class="form-control">
<label class="form-input" for="telNumber">Telephone Number (optional)</label>
<input v-model="telNumber"
:class="{ 'input-error': numberError }"
@input="numberFormatting"
id="telNumber"
type="tel"
placeholder="Enter your telephone number"
class="field-input">
<div v-if="numberError" class="validation-error">
<span class="error-message">Please enter a valid number</span>
</div>
</div>
Although I have a basic validation function in my script to validate the number, it may not be entirely relevant for this specific case.
setup(props) {
const telNumber = ref("");
const numberError = ref(false);
// Run validate form to check whether the data is added
function validateForm() {
if (telNumber.value !== '') {
const numbers = /^[0-9]+$/;
if(!telNumber.value.match(numbers)) {
numberError.value = true;
} else {
numberError.value = false;
}
} else {
numberError.value = false;
}
if (numberError.value) {
AnalyticsHandler.userSendForm(true);
} else if (!numberError.value) {
sendEmail();
}
}