In my React app, I have an input of type "text". My requirements are:-
- User input should be auto-capitalized.
- After the 7th and 13th character, there should be a hyphen ("-") added automatically.
- User input should not exceed 17 characters.
- User can type in only letters and numbers.
This is the simplified HTML element:-
<input
type='text'
maxLength='17'
onChange={event => {
processInput(event);
}}
onKeyDown={event => {
getKey(event);
}}
/>
Here are the onChange
and onKeyDown
functions:-
let lastKeyBackspaceOrDelete;
const getKey = event => {
if(!/[0-9a-zA-Z]/.test(event.key)){
event.preventDefault();
}
lastKeyBackspaceOrDelete = (event.key === 'Backspace' || event.key === 'Delete') ? true : false;
};
const processInput = event => {
if (lastKeyBackspaceOrDelete) {
event.preventDefault();
event.target.value = event.target.value.slice(0, -1);
} else {
if (event.target.value.length === 7 || event.target.value.length === 13) {
event.target.value = event.target.value.concat('-').toUpperCase();
} else {
event.target.value = event.target.value.toUpperCase();
}
}
event.target.value = event.target.value.slice(0, 17);
}
Now this works on my Google Chrome browser on my Mac and on my phone as well. But I'm facing a problem on my phone: if I try to delete a hyphen by pressing Backspace, nothing happens. It deletes other letters and numbers, but gets stuck for hyphens. I'm not facing this issue for my desktop browser though. Why is my function not recognizing the Backspace from a soft keyboard?
Edit: There's a weird behavior I observed on the desktop browser. On pressing Backspace, 2 characters get deleted instead of one. On the mobile browser, only one character gets deleted though.