special characters are accepting in input field . i am using the field for storing the serial number.
serial number is alphanumeric
<ion-input [(ngModel)]="serial_number" (ngModelChange)="validation($event)" #serialno id="serialno" class="cac-input"></ion-input>
validation(event) {
const inputElement = document.getElementById('serialno') as HTMLInputElement;
const pattern = /^[a-zA-Z0-9]*$/;
console.log(event)
console.log(pattern.test(event))
let c = event.replace(/[^a-zA-Z0-9 ]/g, '');
inputElement.value = '';
inputElement.value = c;
console.log(c)
this.serial_number = c;
}
i previously used regex for removing the special characters….but after removing also the value is shown in input field…
i need to prohibit special characters from entering in input field.
in browser , using (keypress) event working fine….but in android (keypress) event is not working
2
Answers
We can write a validator for this, it takes an input regex which it validates for valid and invalid characters, then we do the replace of the unwanted characters with empty string, we also need to lookout for paste events where if invalid characters are pasted they also need to be cleaned, this all can be done using the
@HostListener
property on eventskeydown
andpaste
!directive
html
Stackblitz Demo
Ionic provides an easy one liner using the supoorted pattern attribute on ion-input: