- Issue with text box validation on mobile browsers for my Angular application
- Mobile Browsers: Chrome, Samsung Browser (not working in both)
- Expected Input: Numbers 0-9 and Alphabets A-Z only in the text field
My Approach :
1. Initial Attempt: I attempted to validate using key charCode. It worked on laptop browsers but failed on mobile browsers.
The character code was 229 for every key on phone browsers, hence it did not work.
Code Snippet:
HTML
<input (keypress)="numberOnly($event)" type="text" />
Typescript
numberOnly(event): boolean {
const charCode = event.which ? event.which : event.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
2. Using Directive: I created a directive to handle validation, which also failed on mobile browsers.
Directive Code:
import { Directive, HostListener, ElementRef, Input } from '@angular/core';
@Directive({
selector: '[specialIsAlphaNumeric]'
})
export class SpecialCharacterDirective {
regexStr = '^[a-zA-Z0-9_]*$';
@Input() isAlphaNumeric: boolean;
constructor(private el: ElementRef) { }
@HostListener('keypress', ['$event']) onKeyPress(event) {
return new RegExp(this.regexStr).test(event.key);
}
@HostListener('paste', ['$event']) blockPaste(event: KeyboardEvent) {
this.validateFields(event);
}
validateFields(event) {
setTimeout(() => {
this.el.nativeElement.value = this.el.nativeElement.value.replace(/[^A-Za-z ]/g, '').replace(/\s/g, '');
event.preventDefault();
}, 100)
}
}
3. Using Pattern: Even after trying pattern validation, it didn't work on mobile browsers.
Pattern Used: /[A-Z]{5}\d{4}[A-Z]{1}/i
I implemented validation using Validator.pattern in a reactive form.username: ['', Validators.pattern('/[A-Z]{5}\d{4}[A-Z]{1}/i')],})
HTML
<input formcontrolname='username' (keypress)="numberOnly($event)" type="text" />
Playground : https://codesandbox.io/embed/dazzling-hellman-pygp1?file=/src/app/app.component.html:64-119&codemirror=1