Search code examples
javascriptangulartypescriptangular-directiveformgroups

Angular directive for not allowing only spaces or tabs to be pasted?


Oddball edge case here, I am trying to find a way to prevent the pasting of only spaces or tabs in a fairly lengthy form in the required textareas (to shortcut through the form is their concern), and I guess, if there's a tab or space in front of actual text, then trim it so it's not visible?

I'm working on something along the lines of (within an onPaste(event) in my directive):

const cleanedString = pastedText.replace('/\t/','');

and seeing if it leads with a tab or space, then trim that:

pastedText.charCodeAt(0) === 9/32, etc..

Any ideas? Thank you, this one has been tricky without throwing a $event.preventDefault(); for a valid paste.

Thank you very much for looking!


Solution

  • It turns out event.preventDefault(); was my friend. I skipped the regex and just used trim();

    @HostListener('paste', ['$event'])
    onPaste(event) {
        event.preventDefault();
        let clipboardData = event.clipboardData;
        let pastedText = clipboardData.getData('text');
        let trimmedText = pastedText.trim();
        if (trimmedText.length > 0) {
            this.formControl.control.setValue(trimmedText);
            this.formControl.control.setValidators(this.validators);
            this.formControl.control.updateValueAndValidity();
        } else {
            this.formControl.control.markAsTouched();
        }
    }