Javascript - Removing spaces on paste

Viewed 20686

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.

4 Answers

In case you want to replace anything including Alphabet characters, Arabic characters, uppercase letters, and numbers on paste you can use this function:

cleanPermalink= function(e) {
    e.preventDefault();
    var pastedText = '';
    if (window.clipboardData && window.clipboardData.getData) { // IE
        pastedText = window.clipboardData.getData('Text');
      } else if (e.clipboardData && e.clipboardData.getData) {
        pastedText = e.clipboardData.getData('text/plain');
      }
    // This can replace English, Arabic, and Numbers spaces with (-)
    this.value = pastedText.replace(/[^a-zA-Z؀-ۿ0-9-]+/g,'-');

    // In case you want both Lowercase and Replace spaces use:
    // this.value = pastedText.toLowerCase().replace(/[^a-zA-Z؀-ۿ0-9-]+/g,'-');
};

permalink.onpaste = cleanPermalink;

Hope it can help someone.

Thank you

Related