2
My code
I created the following directive to prevent the user from inserting special characters in inputs.
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appFilterSpecialCharacters]'
})
export class FilterSpecialCharactersDirective {
regexStr = "\\W|_";
regex = new RegExp(this.regexStr);
constructor() {}
@HostListener('keypress', ['$event']) onKeyPress(event) {
return !this.regex.test(event.key);
}
@HostListener('keyup', ['$event']) onKeyUp(event) {
event.target.value = event.target.value.replace(new RegExp(this.regexStr, "g"), "");
}
}
This is an example of input
using the directive
<input appFilterSpecialCharacters type="text" id="inputCep" class="form-control"
placeholder="Entre com o CEP do filiado" formControlName="cep" required autofocus>
And I have the validation as follows
public formulario: FormGroup = new FormGroup({
'matriculacpf': new FormControl(null, [
Validators.required,
Validators.minLength(11),
Validators.maxLength(11)
])
});
My problem
The directive is behaving as predicted, preventing the user to enter with special characters, the problem happens when the user pastes a zip code.
Let’s assume that the user paste "35900777", the validation identifies that the cep has 8 digits and lets pass, but if paste "35900-777" the validation identifies that has 9 digits and does not let pass.
That is the user glue "35900-777", the validation identifies 9 digits the directive removes the "-" but the validation "does not notice" this change and continues blocking even after the directive passes the value to "35900777".
I wanted to insert something in the directive to update the validation, so that it identifies the zip code right after the change.