I am working on validation of an input control when the user copy paste some value in it
On pasting to this input I want to strip out as below:
This is allowed:
abc
abc_123
_123bcd
_123_bcd
This is not:
123abc
123_acd
abc s22
I tried with the below code:
@HostListener('paste', ['$event']) blockPaste(event: KeyboardEvent) {
this.stripInput(event);
}
stripInput(event) {
setTimeout(() => {
this.el.nativeElement.value = this.el.nativeElement.value.replace(/[^A-Za-z ]+/g, '').replace(/\s/g, '');
event.preventDefault();
}, 100);
}
But with above code its not fully working, it doesnt allows: abc_123 _123_ams
Any inputs please
You have made a simple over sight with regards to your initial regex. You did not add a start of string check (which is needed to remove numbers and extra special characters at the start of the string). You will also need another query if you want to remove other special characters from within the string as well
if you change your last block of code to -
@HostListener('paste', ['$event']) blockPaste(event: KeyboardEvent) {
this.stripInput(event);
}
stripInput(event) {
setTimeout(() => {
this.el.nativeElement.value = this.el.nativeElement.value.replace(/^[^A-Za-z_]+/g, '').replace(/[^0-9A-Za-z_]+/g, '').replace(/\s/g, '');
event.preventDefault();
}, 100);
}
It should work as expected (Note the extra ^
at the start of the regex and the added _
to your initial regex as well as the extra following regex).
What this does pin the search to the start of the string instead of allowing it to act on all parts of the string. It works on your abc_123 _123_ams
input and it also strips the extra space in the middle of it as intended. (it makes it abc_123_123_ams
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.