Javascript - Removing spaces on paste

Matt picture Matt · Aug 14, 2012 · Viewed 16.1k times · Source

I have an input text field with a maxlength of 10. The field is for Australian phone numbers (10 digits). Phone numbers are generally split up into the following syntax

12 12345678

If someone copies the above and pastes that into my input field, it obviously leaves the last digit out and keeps the space.

Is there a way to remove any spaces right before it is pasted into the input box? Or is there another work around?

Thanks in advance.

Answer

Paul picture Paul · Aug 14, 2012

This should work for you:

HTML

<input type="text" id="phone" maxlength="10" />​

JavaScript

var phone = document.getElementById('phone'),
    cleanPhoneNumber;

cleanPhoneNumber= function(e)
{
 e.preventDefault();
 var pastedText = '';

 if (e.clipboardData && e.clipboardData.getData)
 {// Standards Compliant FIRST!
  pastedText = e.clipboardData.getData('text/plain');
 }
 else if (window.clipboardData && window.clipboardData.getData)
 {// IE
  pastedText = window.clipboardData.getData('Text');
 }

 this.value = pastedText.replace(/\D/g, '');
};

phone.onpaste = cleanPhoneNumber;

Fiddle: http://jsfiddle.net/y6TYp/6/

Update nnnnnn had a great point regarding Australian phone numbers, updating replace regex.