Home > other >  How to mask all characters except last 3 characters on a string display only
How to mask all characters except last 3 characters on a string display only

Time:05-10

Hi I am working in Angular and in one of the field which is phone number ,I want to mask the string on HTML view only except the last 3 characters. How can I do that ?

Example: - 1212121212 as XXXXXXX212 or *******212

Note: - Only in view I need to show masked. The field is editable and I am patching pre defined value. Once I input new value then mask must not show

<input matInput placeholder='{{"PhoneNumber" | translate}}' formControlName="mobilenumber"
             numbersOnly maxlength="10" minlength="10" required autocomplete="off"
            pattern="[6789][0-9]{9}" title="Please enter valid phone number" inputmode="numeric">

CodePudding user response:

To use in a FormControl you need know when is focus and when not then you can use some like

 [ngModel]="condition?(yourFormControl.value|yourpipe):
            yourFormControl.value"
 (ngModelChange)="! condition && yourFormControl.setValue($event)"

Imagine you has a variable "caracteres" and a FormGroup

  caracteres:number=3;
  form=new FormGroup({
    name:new FormControl()
    mobilenumber:new FormControl(),
    
  })

You can to have some like

<form [formGroup]="form">
     <input matInput 
            (focus)="caracteres=0" 
            (blur)="caracteres=3"  
            [ngModel]="caracteres?(form.get('mobilenumber').value|hideChars):
                       form.get('mobilenumber').value" 
            (ngModelChange)="!caracteres && form.get('mobilenumber').setValue($event)"
            [ngModelOptions]="{standalone:true}"
            >

     <!--see that the rest of your input are in the way-->
     <input formControlName="name"/>
</form>

CodePudding user response:

You could use a pipe, to achieve this

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

@Pipe({
   name: 'hideChars',
})
export class HideCharsPipe implements PipeTransform {
   transform(value: string, minChars = 3): string {
     
      const numHideChar = value.length - minChars;

      const result = [...value].map((char, index) => (index >= numHideChar ? char : '*'));

      return result.join('');
   }
}

And in your view, use like this

{{ mobilenumber | hideChars }}
  • Related