Angular 10: Allow Only Alphabets And Numbers And Restrict Special Characters

Angular 10: Restrict Special Characters in input field

We will learn Angular validation to allow only alphabets and numbers in input field and restrict special characters. Here we will see example where special characters are restricted On keypress, paste and input event.

With this example you will be easily able to restrict special characters and allow only alphabets and numbers in input field.

We have to call a validation function on keypress, paste and input event.

<input class="input" type="text" name="userName" [(ngModel)]="userName" maxlength="8" minlength="8" required (input)="alphaNumberOnly($event)" (keypress)="clsAlphaNoOnly($event)" (paste)="onPaste($event)">
  alphaNumberOnly (e) {  // Accept only alpha numerics, not special characters 
    var regex = new RegExp("^[a-zA-Z0-9 ]+$");
    var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
    if (regex.test(str)) {
        return true;
    }

    e.preventDefault();
    return false;
  }

  onPaste(e) {
    e.preventDefault();
    return false;
  }

Lets see full example

src/app/app.component.html

<h1>Angular Restrict Special Characters in input field - techCruds.com</h1>
  
<input class="input" type="text" name="userName" [(ngModel)]="userName" maxlength="8" minlength="8" required (input)="alphaNumberOnly($event)" (keypress)="clsAlphaNoOnly($event)" (paste)="onPaste($event)">

src/app/app.component.ts

import { Component, VERSION } from '@angular/core';
  
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular ' + VERSION.major;
  
  alphaNumberOnly (e) {  // Accept only alpha numerics, not special characters 
    var regex = new RegExp("^[a-zA-Z0-9 ]+$");
    var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
    if (regex.test(str)) {
        return true;
    }

    e.preventDefault();
    return false;
  }

  onPaste(e) {
    e.preventDefault();
    return false;
  }
}

Also Read: https://techcruds.com/angular-display-records-count-example/

Reference:

String.fromCharCode()

Share via
Copy link
Powered by Social Snap