Ion-input pattern validation

I am taking input test_key from user using below code.

<ion-input type="text" [(ngModel)]="test_key"></ion-input>

But I need to ensure that user only enter alphabets not other characters.

I already try with
<ion-input type="text" [(ngModel)]="test_key" pattern="[A-Za-z]{20}"></ion-input>

But this will not work for me.

Add input event like this.
<ion-input type="text" [(ngModel)]="test_key" (input)="getText($event)"></ion-input>

And then in your ts file add getText method.

getText(e){
   var elementValue = e.srcElement.value;
   if(elementValue){
     var regex = /^[A-z]+$/;   
      var tempValue = elementValue.substring(0, elementValue.length - 1);
      if (!regex.test(elementValue)) {
        console.log("Entered char is not alphabet");
        e.srcElement.value = tempValue;
      }
   }
 }

I don’t know if this is the best way to go.

1 Like