74 lines
2.3 KiB
JavaScript
74 lines
2.3 KiB
JavaScript
// Phone validation and formatting function
|
|
export function validatePhoneLive(inputEl) {
|
|
// Get current value and remove any non-digit characters
|
|
let val = inputEl.value.replace(/\D/g, '');
|
|
|
|
// Format the phone number as 123-456-7890
|
|
let formattedValue = '';
|
|
if (val.length > 0) {
|
|
formattedValue = val.substring(0, 3);
|
|
if (val.length > 3) {
|
|
formattedValue += '-' + val.substring(3, 6);
|
|
}
|
|
if (val.length > 6) {
|
|
formattedValue += '-' + val.substring(6, 10);
|
|
}
|
|
}
|
|
|
|
// Update the input value with formatted version
|
|
inputEl.value = formattedValue;
|
|
|
|
// Check if the phone number is valid (exactly 10 digits)
|
|
const valid = val.length === 10;
|
|
|
|
// Update validation UI - add red border for invalid input
|
|
if (val.length === 0) {
|
|
inputEl.classList.remove('is-invalid', 'is-valid');
|
|
} else if (valid) {
|
|
inputEl.classList.remove('is-invalid');
|
|
inputEl.classList.add('is-valid');
|
|
} else {
|
|
inputEl.classList.remove('is-valid');
|
|
inputEl.classList.add('is-invalid');
|
|
}
|
|
|
|
return valid;
|
|
}
|
|
|
|
// Prevent form submission if phone is invalid
|
|
function preventInvalidSubmission() {
|
|
const forms = document.querySelectorAll('form');
|
|
forms.forEach(form => {
|
|
form.addEventListener('submit', function (e) {
|
|
const phoneInput = document.getElementById('phoneInput');
|
|
if (phoneInput && !validatePhoneLive(phoneInput)) {
|
|
e.preventDefault();
|
|
phoneInput.focus();
|
|
return false;
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
// Initialize the event listener when the page loads
|
|
document.addEventListener('DOMContentLoaded', function () {
|
|
const phoneInput = document.getElementById('phoneInput');
|
|
|
|
// Add input event listener for live validation and formatting
|
|
phoneInput.addEventListener('input', function () {
|
|
validatePhoneLive(this);
|
|
});
|
|
|
|
// Add blur event listener to finalize formatting
|
|
phoneInput.addEventListener('blur', function () {
|
|
validatePhoneLive(this);
|
|
});
|
|
|
|
// Add focus event to select all text when focused
|
|
phoneInput.addEventListener('focus', function () {
|
|
this.select();
|
|
});
|
|
|
|
// Prevent form submission for invalid phone numbers
|
|
preventInvalidSubmission();
|
|
}); |