Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular directive to handle mouse paste by cleaning string from clipboard

I’m so close.

My input is a number input, with a increment=".000001" and hiding the spin buttons.

In my directive I have:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@HostListener('paste', ['$event'])
onPaste(event: ClipboardEvent) {
    console.log('You have pasted successfully');
    const input = event.target as HTMLInputElement;
    let clipboardData = event.clipboardData;
    let pastedText = clipboardData.getData('text').toUpperCase();
    console.log("pastedText: " + pastedText);
    let trimmedText = pastedText.replace(/\s|[A-Z_]|[#$%,^&*()]/g, '');
    console.log("trimmedText: " + trimmedText);
    (event.target as HTMLInputElement).value = trimmedText;
}

if I paste, with mouse right click or ctrl + v paste, the string: sd87634ee5jkbhsdf74bhgf.34iuhsdef76

event.target.value = trimmedText;
console.log("trimmedText: " + trimmedText);
trimmedText equals 87634574.3476, so the initial string is cleaned perfectly..

but when the function is completed, it appends a messier version 87634574.347687634e5743476

What’s going on here?

>Solution :

you’ll need to add this at the top of your function:

event.preventDefault();

to actually stop the native paste event from executing after you set the input value.

right now you’re just setting a value 87634574.3476 then the paste is executing and appending the pasted value 87634e5743476 which is your pasted value without invalid number characters (yes, one e is a valid number character).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading