Facebook Pixel

How do you implement paste support in an OTP input component?

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.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in OTP Input Paste Support Implementation in JavaScript

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.

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

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.