JSFiddle - React, Tailwind, and code Playground
by nathanlogan
HTML
<label>Enter Studio Project ID:
<input type="text" placeholder="555-555-555" oninput="handleInput(event)" onkeydown="handleKeyDown(event)">
</label>
CSS
body {
padding: 50px;
font-family: Roboto, sans-serif;
}
input {
display: block;
margin: 10px;
padding: 5px;
border-radius: 5px;
border-width: 1px;
border-color: #333;
}
JavaScript
const filterAndFormatNumbers = (input) => {
// Remove all non-numeric and non-hyphen characters
let filtered = input.replace(/[^\d-]/g, '');
// Remove existing hyphens and limit to a maximum of 9 numbers
filtered = filtered.replace(/-/g, '').slice(0, 9);
// Add hyphens every 3 numbers
let formatted = filtered.replace(/(\d{3})/g, '$1-');
// Limit to a maximum of 11 characters (including hyphens)
formatted = formatted.slice(0, 11);
return formatted;
};
const handleInput = (event) => {
const inputElement = event.target;
const cursorPosition = inputElement.selectionStart;
const previousValue = inputElement.value;
const formattedValue = filterAndFormatNumbers(inputElement.value);
inputElement.value = formattedValue;
// Adjust cursor position to the end if a hyphen was added
if (formattedValue.length > previousValue.length) {
inputElement.setSelectionRange(formattedValue.length, formattedValue.length);
} else {
inputElement.setSelectionRange(cursorPosition, cursorPosition);
}
};
const handleKeyDown = (event) => {
const inputElement = event.target;
const cursorPosition = inputElement.selectionStart;
// Check if the user is deleting a character
if (event.key === 'Backspace' && inputElement.value[cursorPosition - 1] === '-') {
// Prevent the default backspace action
event.preventDefault();
// Remove the character before the hyphen
const newValue = inputElement.value.slice(0, cursorPosition - 2) + inputElement.value.slice(cursorPosition);
inputElement.value = filterAndFormatNumbers(newValue);
// Adjust cursor position
inputElement.setSelectionRange(cursorPosition - 2, cursorPosition - 2);
}
};