skip to Main Content

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

In app the field shows

consoling the ngmodel field shows

2

Answers


  1. 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 events keydown and paste!

    directive

    import { Directive, ElementRef, HostListener, Input } from '@angular/core';
    
    @Directive({
      selector: '[appPattern]',
    })
    export class PatternDirective {
      @Input() appPattern: string = '[A-Za-z0-9]';
    
      @HostListener('keyup', ['$event']) public onKeydown(event: any) {
        const value: string = event.target.value;
        if (!value) {
          return true;
        }
        const regExpr = new RegExp(`^(${this.appPattern})+$`);
        if (!regExpr.test(value)) {
          event.target.value = value.replace(
            new RegExp(`(${this.appPattern})|.*`, 'gm'),
            '$1'
          );
          event.preventDefault();
          return false;
        }
      }
    
      @HostListener('paste', ['$event']) public onPaste(event: any) {
        event.preventDefault();
        let clipboardText = event.clipboardData.getData('text');
        event.target.value = clipboardText.replace(
          new RegExp(`(${this.appPattern})|.*`, 'gm'),
          '$1'
        );
      }
      constructor(private elementRef: ElementRef) {}
    }
    

    html

     <ion-input
        type="text"
        [(ngModel)]="todo.title1"
        name="title1"
        appPattern="[A-Za-z0-9]"
      ></ion-input>
    

    Stackblitz Demo

    Login or Signup to reply.
  2. Ionic provides an easy one liner using the supoorted pattern attribute on ion-input:

    <ion-input type="text" pattern="^[a-zA-Z0-9]*$" ></ion-input>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search