3

I'm running into an issue where when I run either

<input type="text" (keydown)="testKeyCodes($event)"/>
<!-- or -->
<input type="text" (keyup)="testKeyCodes($event)"/>

I always get a keyCode of 229 in android chrome browsers, I know this has been mentioned several times on stack overflow, and I've seen the recommendation to use

<input type="text" (keypress)="testKeyCodes($event)"/>

instead. Problem is, the keypress event is not fired by android phones. Has anyone found a solution for this?

My end goal is to prevent users on android browsers from entering special characters into my alphanumeric inputs.

Below is my Regex that I'd like to check against.

//tried this
testKeyCodes(event) {
    if (!/[a-zA-Z0-9 ]/.test(event.keyCode) && event.keyCode != '8') {
        event.preventDefault();
    }
}

//and this
testKeyCodes(event) {
    if (!/[a-zA-Z0-9 ]/.test(String.fromCharCode(event.keyCode)) && event.keyCode != '8') {
        event.preventDefault();
    }
}

Any assistance would be greatly appreciated. I'm completely stuck.

BSlink
  • 141
  • 2
  • 6
  • Possible duplicate of [Capture keys typed on android virtual keyboard using javascript](https://stackoverflow.com/questions/30743490/capture-keys-typed-on-android-virtual-keyboard-using-javascript) – reyiyo Oct 10 '17 at 19:03

1 Answers1

0

I would write a directive which would listen to input event with a custom validator, something like the following:

....
@HostListener('input',['$event']) 
    onInput($event){
      let newValue = this.el.nativeElement.value;
      ...   
      let patternValidation=newValue.match(myPattern); //replace here with your regexp

      if(patternValidation){
         //keep input
      } else {
         //exclude input
         newValue = patternValidation;
      }

      this.model.control.setValue(newValue);
  }

  <input myDirective [(ngModel)]="value" name="value" >

This is a roughly described you may want to make it more detailed.

Vega
  • 27,856
  • 27
  • 95
  • 103