anon
anon

Reputation:

Angular 6 restrict certain alphabets

I have the following input field. I am trying to only allow a user to enter alphabets from A-F. If the user tries to enter an alphabet outside of the range then the alphabet should be trimmed on the fly i.e there is no button to verify if its valid input or not. The input field also allows numbers and special characters.

<mat-form-field>
  <input matInput (keyup)="MACAddressInput()" placeholder="MAC address" name="mac_address" required [(ngModel)]="model.mac_address" (blur)="validate()">
  <mat-error *ngFor="let error of errors_by_field['mac_address']">{{error.message}}</mat-error>
</mat-form-field>

  MACAddressInput() {
    if (this.model.mac_address) {
      const inputColon = this.model.mac_address.replace(new RegExp(':', 'g'), '').trim();
      const MAC_blocks = inputColon.match(/.{1,2}/g);
      let formatedMac = MAC_blocks.shift();
      for (const block of MAC_blocks) {
       formatedMac = formatedMac + ':' + block;
      }
      this.model.mac_address = formatedMac.toUpperCase();
    }
  }

I tried with html patterns but it allows a user to input anything

Upvotes: 0

Views: 1946

Answers (2)

Shreenil Patel
Shreenil Patel

Reputation: 1094

Incase if you want to do it with simple binding function

Code:

MACAddressInput(e) {
   let code = e.key.charCodeAt(0);
   if ((code >= 65 && code <= 90) || (code >= 97 && code <= 122)) {}
   else {
     e.preventDefault();
     return;
   }
}

HTML:

<input matInput (keydown)="MACAddressInput($event)" placeholder="MAC address" name="mac_address" required [(ngModel)]="model.mac_address" (blur)="validate()">

Note : Make sure you use (keydown) event. This code will allow A-Z and a-z.

Upvotes: 2

Jacopo Sciampi
Jacopo Sciampi

Reputation: 3443

You can create a custom pipe to do that.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'myCustomPipe'
  })
  export class MyCustomPipe implements PipeTransform {
    transform(input: string): string {
        let newString = "";
      for(let i=0; i<= input.length; i++){
        var char = input.charAt(i);
        if(char.charCodeAt(0) >= 65 && char.charCodeAt(0) <=70){
            newString += char;
        }
      }

      return newString;
    }
  }

Then add it into your module

 declarations: [
    ...
    MyCustomPipe,
    ...
]

Call it into your .html component in this way

{{ myText | myCustomPipe }}

I've done a test, with myText = "ABCG"; my pipe trimmed the text to ABC.

To do the magic inside your function:

if (this.model.mac_address) {
    let newString = "";
    for(let i=0; i<= this.model.mac_address.length; i++){
        var char = this.model.mac_address.charAt(i);
        if(char.charCodeAt(0) >= 65 && char.charCodeAt(0) <=70){
            newString += char;
        }
    }
    this.model.mac_address = newString.toUpperCase();
}

Upvotes: 2

Related Questions