Javascript - Removing spaces on paste

Approaching the task you described you want to make sure that your code works in different browsers with or without javascript so I would do the following:

  1. Set the maxlength to 11 - maxlength is an HTML attribute and you need to make sure that with or without javascript the data entered by the user is not lost. If the user enters 11 digits and there is no javascript - you will need to capture the data and cleanse it from the server side. Well, server side validation is mandatory.

  2. If the javascript is there I would use the jquery function to set the maxlength and ensure that the spaces are removed, so say you have a field with ID = 'title': on document ready you write the following code:

    $('input#title').attr('maxLength','10').keypress(limitMe);

    function limitMe(e) {
        if (e.keyCode == 32) { return true; }
        return this.value.length < $(this).attr("maxLength");
    }
    

Obviously if you have numerous fields you just decorate all of the input fields with the same class attribute and then apply it to all the fields like so:

$('input.limited').attr('maxLength','10').keypress(limitMe);

This function will help you do it:

function removeSpaces(string) {
 return string.split(' ').join('');
}

Alternatively, using jQuery, you can use the method described here: Delete white spaces in textbox when copy pasted with jquery


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.