Why do you need preventDefault for paste in an OTP input?
Because the default paste would fill only the current input with the entire pasted string (which exceeds maxlength=1, so only the first character is kept). preventDefault lets you control how the pasted text is distributed across the inputs.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in OTP Input Paste Support Implementation in JavaScript
Listen for the paste event, prevent default, get the pasted text from clipboardData, filter to numeric only with replace(/\D/g, ''), split into characters, and fill each input starting from the current index. Focus the last filled input and check completion.
Check if index + i < inputs.length before filling each input: if (index + i < inputs.length) inputs[index + i].value = char. Extra characters are ignored. Focus the last input: Math.min(index + pasted.length, inputs.length - 1).
Use replace(/\D/g, '') on the pasted text: const pasted = e.clipboardData.getData('text').replace(/\D/g, ''). This removes all non-digit characters before splitting and filling the inputs.
Still have questions?
Browse all our FAQs or reach out to our support team
